[Tutor] Sorting a list of lists aka nested lists

Alan G alan.gauld at freenet.co.uk
Sun Aug 14 09:32:48 CEST 2005

>    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...


Alan G. 

More information about the Tutor mailing list