sort by last then by first

Peter Abel p-abel at t-online.de
Tue Jan 28 15:57:37 EST 2003


bk at whack.org (Brian Kranson) wrote in message news:<1964c4d7.0301271648.18dba0b3 at posting.google.com>...
> 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']]
> 
I think you're quite near.

> 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

If you change the order of sorting from
low order key to high order key, I can't see
any reason, why this shouldn't work stable.

With this technique you can sort list with
multiple elment sequences.
e.g.
l is an unsorted list with lists as elements each with 3 names:

>>> print '\n'.join(map(str,l))
['Flintstone', 'John', 'Peter']
['Kennedey', 'James', 'Peter']
['Flintstone', 'James', 'John']
['Flintstone', 'John', 'Harvey']
['McLarren', 'John', 'Peter']
['Flintstone', 'James', 'Sven']
['McLarren', 'Peter', 'Peter']
['Kennedey', 'John', 'Harvey']
['McLarren', 'Sven', 'Harvey']
['McLarren', 'Peter', 'Sven']
['Miller', 'Sven', 'Peter']
['Flintstone', 'James', 'Sven']
['Miller', 'John', 'James']
['Kennedey', 'James', 'Peter']
['Flintstone', 'Harvey', 'Harvey']

# 1) Sort by 3rd name
>>> l.sort(lambda a,b:cmp(a[2],b[2]))
# 2) Sort by 2nd name
>>> l.sort(lambda a,b:cmp(a[1],b[1]))
# 3) Sort by 1st name
>>> l.sort()

>>> print '\n'.join(map(str,l))
['Flintstone', 'Harvey', 'Harvey']
['Flintstone', 'James', 'John']
['Flintstone', 'James', 'Sven']
['Flintstone', 'James', 'Sven']
['Flintstone', 'John', 'Harvey']
['Flintstone', 'John', 'Peter']
['Kennedey', 'James', 'Peter']
['Kennedey', 'James', 'Peter']
['Kennedey', 'John', 'Harvey']
['McLarren', 'John', 'Peter']
['McLarren', 'Peter', 'Peter']
['McLarren', 'Peter', 'Sven']
['McLarren', 'Sven', 'Harvey']
['Miller', 'John', 'James']
['Miller', 'Sven', 'Peter']
>>> 
Though I can't say anything about speed.
Peter




More information about the Python-list mailing list