How to sort a list of tuples
Denis S. Otkidach
ods at strana.ru
Fri Nov 19 05:55:15 EST 2004
On Fri, 19 Nov 2004 18:22:45 +0800
Valkyrie <valkyrie at cuhk.edu.hk> wrote:
> I have a list of tuples, and one of the fields in the tuple is score. So how can
> I sort the list by the score?
In 2.4 you can use key argument of sort method:
>>> l = [('a', 2), ('c', 3), ('b', 1)]
>>> l.sort(key=lambda i: i[1])
>>> l
[('b', 1), ('a', 2), ('c', 3)]
otherwise pass comparison function:
>>> l = [('a', 2), ('c', 3), ('b', 1)]
>>> l.sort(lambda i1, i2: cmp(i1[1], i2[0]))
>>> l
[('b', 1), ('c', 3), ('a', 2)]
--
Denis S. Otkidach
http://www.python.ru/ [ru]
More information about the Python-list
mailing list