sorting a list of lists

Tuomas tuomas.vesterinen at pp.inet.fi
Mon Aug 27 22:42:15 CEST 2007


 >>> records = [['dog',1,2], ['chair',2,1], ['cat',1,3], ['horse',3,4],
... ['table',3,2], ['window',3,5]]
 >>> sorted(records, key = lambda x: (x[1], x[2]))
[['dog', 1, 2], ['cat', 1, 3], ['chair', 2, 1], ['table', 3, 2], 
['horse', 3, 4], ['window', 3, 5]]


nicksavill at googlemail.com wrote:
> Hi,
> 
> i would like to sort a list of lists. The list is first sorted on the
> second item in the sub-lists (which I can do), then on the third item
> (which I can't).
> 
> eg. records = [['dog',1,2], ['chair',2,1], ['cat',1,3], ['horse',3,4],
> ['table',3,2], ['window',3,5]]
> 
> I want sorted to [['dog',1,2], ['cat',1,3], ['chair',2,1], ['table',
> 3,2], ['horse',3,4], ['window',3,5]]
> 
> To sort on the second item in the sub-lists I do the following
> 
> pass1 = itemgetter(1)
> sorted(records, key=pass1)
> 
> How can I then sort on the third item in the sub-lists whilst keeping
> the order on the second item?
> 
> Nick
> 



More information about the Python-list mailing list