sort by last then by first

Brian Kranson bk at whack.org
Mon Jan 27 19:48:27 EST 2003


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

>>> names=[['Flintstone', 'Fred'],['Flintstone', 'Wilma'],['Rubble',
'Barney'],['Rubble', 'Betty'],['Flintstone', 'Pebbles']]
>>> names.sort() #this will sort by last name
>>> print names
[['Flintstone', 'Fred'], ['Flintstone', 'Wilma'], ['Rubble',
'Barney'], ['Rubble', 'Betty'], ['Flintstone', 'Pebbles']]

and i know i can do ...

>>> names=[['Flintstone', 'Fred'],['Flintstone', 'Wilma'],['Rubble',
'Barney'],['Rubble', 'Betty'],['Flintstone', 'Pebbles']]
>>> names.sort(lambda a, b: cmp(a[1], b[1])) #this will sort by first
name
>>> print names
[['Rubble', 'Barney'], ['Rubble', 'Betty'], ['Flintstone', 'Fred'],
['Flintstone', 'Pebbles'], ['Flintstone', 'Wilma']]

but what i don't know is if this will always work.  seems like the
sort is what i am looking for, but i can't tell if it is by chance or
if my logic is correct.
i want to sort by last name then by first name.

thanks
Bk




More information about the Python-list mailing list