sort by last then by first

Anton Vredegoor anton at vredegoor.doge.nl
Tue Jan 28 10:36:19 EST 2003


On 27 Jan 2003 16:48:27 -0800, bk at whack.org (Brian Kranson) wrote:

>is is possible to sort a list by one field and then by another field
>in the list.  for example....

As long as its possible to compare each pair of items without knowing
anything about the other items it should be possible to write a
specialized comparing function.

This seems to work (not thoroughly tested):

def specialcompare(a,b):
    (a1,a2),(b1,b2) = a,b
    if a1 < b1:
        return 1
    if a1 == b1:
        return cmp(a2,b2)
    return -1

def test():
    names=[['Flintstone', 'Fred'],['Flintstone', 'Wilma'],['Rubble',
        'Barney'],['Rubble', 'Betty'],['Flintstone', 'Pebbles']]  
    names.sort(specialcompare)
    print names


if __name__=='__main__':
    test()

output:
[['Rubble', 'Barney'], ['Rubble', 'Betty'], ['Flintstone', 'Fred'],
['Flintstone', 'Pebbles'], ['Flintstone', 'Wilma']]







More information about the Python-list mailing list