1

I'm trying to compare things in list, tuple, etc. and I'm wondering how we specify what we want to compare. I want to sort a list: [('A',(6,2,1,3)), ('B',(4,5,9,3)), ('C',(1,2,3,8))] by the last number, and if the last number is equal, then sort by the 3rd number. However, I'm unsure how to approach this. I used lambda to sort by the last number, but when the last numbers are equal, python automatically sorts by the first number.

2 Answers 2

3

Using the lambda, create a key which is a tuple of last number and third number:

mylist = [('B',(4,5,9,3)), ('C',(1,2,3,8)), ('A',(6,2,1,3))]
mylist.sort(key=lambda x:(x[1][-1], x[1][2]))

Outputs:

[('A', (6, 2, 1, 3)), ('B', (4, 5, 9, 3)), ('C', (1, 2, 3, 8))]
Sign up to request clarification or add additional context in comments.

Comments

0

You basically want to sort by the last element in each tuple, reversed. Python translates that english to code pretty well:

sorted(li,key=lambda x: tuple(reversed(x[-1])))
Out[4]: [('A', (6, 2, 1, 3)), ('B', (4, 5, 9, 3)), ('C', (1, 2, 3, 8))]

3 Comments

taken literally, OP didn't actually say sort by 2nd and 1st elements, but you're probably right
yeah, I extrapolated a bit.
that's no reason to downvote this answer. c'mon guys! it's still perfectly valid!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.