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

Duncan Booth duncan.booth at invalid.invalid
Sun Feb 10 00:44:37 EST 2008


thebjorn <BjornSteinarFjeldPettersen at gmail.com> wrote:

> I'm not sure which Python is default for Ubuntu 6.06, but assuming you
> can access a recent one (2.4), the list.sort() function takes a key
> argument (that seems to be rather sparsely documented in the tutorial
> and the docstring...). E.g.:
> 
>>>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
>>>> lst.sort(key=lambda (a,b,c):(c,b))
>>>> lst
> [(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]
>>>>

It may be simpler just to use the key argument multiple times (not 
forgetting to specify the keys in reverse order, i.e. the most significant 
comes last). So with this example, sorting by column 2 then column 1 and 
ignoring column 0 can be done by:

>>> 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)]


or even:

>>> from operator import itemgetter
>>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
>>> for keycolumn in reversed([2,1]):
	lst.sort(key=itemgetter(keycolumn))

	
>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]

The important point here is to remember that the sort is stable (so you can 
do multiple sorts without disrupting earlier results).



More information about the Python-list mailing list