How to sort a list of tuples
Craig Ringer
craig at postnewspapers.com.au
Fri Nov 19 05:53:57 EST 2004
More information about the Python-list mailing list
Fri Nov 19 05:53:57 EST 2004
- Previous message (by thread): How to sort a list of tuples
- Next message (by thread): How to sort a list of tuples
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Fri, 2004-11-19 at 18:22, Valkyrie 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?
Assuming the score field is index 1 of each tuple:
def cmp(a,b):
if a[1] < b[1]:
return -1
elif a[1] > b[1]:
return 1
else:
return 0
my_tuple_list.sort(cmp)
(technically the elifs could be ifs, and the final else could be omitted
in favour of just 'return 0', but for clarity the above is IMO best).
see 'help(list.sort)' for more information.
To whoever added this fantastic feature, thanks and more thanks. It's
saved me so much work at times that it's just crazy.
--
Craig Ringer
- Previous message (by thread): How to sort a list of tuples
- Next message (by thread): How to sort a list of tuples
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list