[Tutor] Sorting a list of lists aka nested lists

Kent Johnson kent37 at tds.net
Mon Aug 15 13:42:14 CEST 2005


jfouhy at paradise.net.nz wrote:
> Note that in Python2.4+, you can use key= instead:
> 
> def sortKey(lst):
>  return lst[2]
> Quant.sort(key=sortKey)
> 
> This is more effient than specifying a different comparison function, because
> the key function is only called once for each element.

And instead of defining your own function you can use itertools.itemgetter() which is intended for this purpose:
import itertools
Quant.sort(key=itertools.itemgetter(2))

Kent



More information about the Tutor mailing list