How to sort this kind of list easily?

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Sun Aug 22 17:14:31 EDT 2004


Scott David Daniels wrote:
> Ben Last wrote:
>>>From: Anthony Baxter, in response to BruceKL WhoH
>>>list.sort sorts tuples by first argument, then second &c. If you want a
>>>custom sort order, look at the decorate-sort-undecorate pattern.
>> 
>> 
>> Or if you want to sort only on your Id, use a lambda:
>> l.sort(lambda x,y: cmp(x[0],y[0]))
>> 
>> To force sorting on just the nth element of the tuples, replace 0 with n in
>> the above.
>> 
>> b
>> 
> If you are using 2.4 (now in beta), you could also do:
> 
> lst.sort(key=lambda element:element[1])

_If_ you are using 2.4, better use:

lst.sort(key=operator.itemgetter(1))

Reinhold

-- 
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich.  Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
  -- David Kastrup in de.comp.os.unix.linux.misc



More information about the Python-list mailing list