Is there an easy way to sort a list by two criteria?

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Feb 11 10:47:18 CET 2008


[repost]

Duncan Booth:
> >>> from operator import itemgetter
> >>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
> >>> lst.sort(key=itemgetter(1))
> >>> lst.sort(key=itemgetter(2))
> >>> lst
> [(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]

A little known thing from Python 2.5:

>>> from operator import itemgetter
>>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
>>> sorted(lst, key=itemgetter(2, 1))
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]

Bye,
bearophile



More information about the Python-list mailing list