sorting list of tuples by second (third...) tuple item

Justin Sheehy justin at iago.org
Thu Feb 14 15:25:57 EST 2002


stojek at part-gmbh.de (Marcus Stojek) writes:

> How can I sort a list of tuples (all tuples have 4 float items)
> by the second (or third or n-th) tuple item. And I have to
> do it fast.

Python's builtin sort is fairly fast, all you need to handle is the indexing.

The straightforward way would be:

lst.sort(lambda a,b: cmp(a[2], b[2]))

or if you don't like lambda:

def cmp3(a, b):
    return cmp(a[2], b[2])
lst.sort(cmp3)

If you want more speed, you may want to decorate the list first:

newlst = [(x[2], x) for x in lst]
newlst.sort()
lst = [x[1] for x in newlst]

-Justin

 





More information about the Python-list mailing list