Cole
Cole

Reputation: 2509

Python: sorting a list using two keys which sort in a different direction

>>> 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?

Upvotes: 4

Views: 1857

Answers (1)

nneonneo
nneonneo

Reputation: 179592

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)

Upvotes: 8

Related Questions