Monday, 15 June 2015

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



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

>>> 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 want sort reverse=false on sec key. in other words, want result be:

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

how do this?

for sorting numbers, can utilize negative sort key:

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

alternately, if have non-numeric info can two-pass sort (sorting least-significant key first):

ol = sorted(ul, key=lambda x: x[1]) ol = sorted(ol, key=lambda x: x[0], reverse=true)

python

No comments:

Post a Comment