[Tutor] I can't work out how to sort lists of lists
Corran Webster
cwebster@nevada.edu
Mon, 19 Mar 2001 13:39:11 -0800
At 9:23 AM +1200 20/3/01, Phil Bertram wrote:
>Hi all,
>
>I have a list thus,
>
>a=[ (8,9,10), (1,2,3), (5,6,7) ]
>
>I wish to sort the list by the second element of each tuple.
>
>I can not seem to work out how to get the sort method's compare
>function to work.
>
>Any ideas ?
Perhaps the simplest way is to define your own comparison function:
def cmpsecond(x, y):
return cmp(x[1], y[1])
a.sort(cmpsecond)
should do the trick. You can write it more concisely with a lambda as:
a.sort(lambda x, y: cmp(x[1], y[1]))
For more info on tricks you can use with custom comparison functions,
see the Sorting Mini-HOWTO.
http://py-howto.sourceforge.net/sorting/sorting.html
Regards,
Corran