sort by last then by first

Jørgen Cederberg jorgencederberg at hotmail.com
Tue Jan 28 02:14:35 EST 2003


Brian Kranson wrote:
> is is possible to sort a list by one field and then by another field
> in the list.  for example....
> 
> names=[['Flintstone', 'Fred'],['Flintstone', 'Wilma'],['Rubble',
> 'Barney'],['Rubble', 'Betty'],['Flintstone', 'Pebbles']]
> 
> in this case i know i can do ...
> 
< snip - example with lambda >

When sorting a list by several fields, I use this method:

 >>> names=[['Flintstone', 'Fred'],['Flintstone', 'Wilma'],['Rubble',
... 'Barney'],['Rubble', 'Betty'],['Flintstone', 'Pebbles']]
 >>> snames = [ (x[1], x[0], x) for x in names]
 >>> snames.sort()
 >>> sortednames = [x[-1] for x in snames]
 >>> sortednames
[['Rubble', 'Barney'], ['Rubble', 'Betty'], ['Flintstone', 'Fred'], 
['Flintstone
', 'Pebbles'], ['Flintstone', 'Wilma']]
 >>>

I create a list of tuples, where the tuple is ordered in the way I want 
to sort, i.e. "sort by last then by first". The last element is the 
original item to be sorted. Sort them, and then extract the original item.

Maybe there are faster and easier ways, but I understand this one.

Regards
Jorgen





More information about the Python-list mailing list