How to sort a list of tuples
Jeff Shannon
jeff at ccvcorp.com
Fri Nov 19 15:22:27 EST 2004
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?
>
>Thanks in advance
>
>
Others have showed the possibility of a comparison function, but often
it's faster to use the decorate-sort-undecorate pattern:
def sort_on(list_to_sort, field_num):
templist = [ (item[field_num], item) for item in list_to_sort ]
templist.sort()
return [ item[1] for item in templist ]
Note that I'm creating a new list, leaving the original list unsorted.
You can easily rebind the original name to the sorted list if needed --
mylist = sort_on(mylist, 3)
I believe that using the key=... in 2.4 is faster than this DSU pattern,
but DSU is typically faster than using a cmp() function/lambda.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list