4
>>> from operator import itemgetter
>>> ul = [(10,2),(9,4),(10,3),(10,4),(9,1),(9,3)]
>>> ol = sorted(ul, key=itemgetter(0,1), reverse=True)
>>> ol
[(10, 4), (10, 3), (10, 2), (9, 4), (9, 3), (9, 1)]

What I want is to sort reverse=False on the second key. In other words, I want the result to be:

[(10, 2), (10, 3), (10, 4), (9, 1), (9, 3), (9, 4)]

How do I do this?

1 Answer 1

8

For sorting numbers, you can use a negative sort key:

sorted(ul, key=lambda x: (-x[0], x[1]))

Alternately, if you have non-numeric data you can do a two-pass sort (sorting by the least-significant key first):

ol = sorted(ul, key=lambda x: x[1])
ol = sorted(ol, key=lambda x: x[0], reverse=True)
Sign up to request clarification or add additional context in comments.

1 Comment

I was going to suggest the two pass sort... As a list.sort method is a stable sort - this works nicely

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.