[Tutor] Sorting a list of lists aka nested lists

jfouhy@paradise.net.nz jfouhy at paradise.net.nz
Mon Aug 15 01:18:26 CEST 2005

Quoting Alan G <alan.gauld at freenet.co.uk>:

> > Quant.append( [ db_ticker, stock_close, MTD, 0, QTD, 0, YTD, 0, 
> > 0, 0 ] )
> > After Quant is created, I want to sort it by MTD. If I use a simple 
> > Quant.sort(), I assume its going to sort by 'db_ticker' which is not 
> > what I want.
> you need to write your own comparison function.
> Basically it will take two of your lists and return -1,0 or 1.
> Or you can use Python's own logic to help
> def cmplists(lst1,lst2):
>  return cmp(lst1[2],lst2[2])
> Now you can sort Quant by passing your function into sort...

Note that in Python2.4+, you can use key= instead:

def sortKey(lst):
 return lst[2]

This is more effient than specifying a different comparison function, because
the key function is only called once for each element.


More information about the Tutor mailing list