[Tutor] sorting nested tuples
Yigal Duppen
yduppen at xs4all.nl
Sat Oct 18 08:23:30 EDT 2003
> x = [('hello', 2), ('goodbye', 3), ('python', 1)]
>
> how would i sort it by the 2 variable or any variable for that matter.
Hi Conrad,
Apart from the decorate-sort-undecorate pattern described by Danny, you can
also pass a comparator function to the sort method of a list.
First, define a comparator that compares on the second element of a tuple:
>>> def cmpOnSecond(t1, t2):
... return cmp(t1[1], t2[1])
And the use that function:
>>> mylist = [('hello', 2), ('goodbye', 3), ('python', 1)]
>>> mylist.sort(cmpOnSecond)
>>> mylist
[('python', 1), ('hello', 2), ('goodbye', 3)]
If you're more into anonymous functions, this works too:
>>> mylist = [('hello', 2), ('goodbye', 3), ('python', 1)]
>>> mylist.sort(lambda t1,t2: cmp(t1[1], t2[1]))
>>> mylist
[('python', 1), ('hello', 2), ('goodbye', 3)]
For simple cases like this, I prefer the comparator function above the
decorate-sort-undecorate approach.
YDD
--
http://www.xs4all.nl/~yduppen
More information about the Tutor
mailing list