The Python Book
sort tuple

Sort a list of tuples

Say you have markers that are tuples, and you want to have the marker list sorted by the first tuple element.

sorted_marker=sorted( marker, key=lambda x:x[0] ) 

Multi-level sort: custom compare

Use a custom compare function. The compare function receives 2 objects to be compared.

def cust_cmp(x,y):
    if (x[1]==y[1]):
        return cmp( x[0],y[0] )    
    return cmp(x[1],y[1])

names= [ ('mahalia', 'jackson'),  ('moon', 'zappa'), ('janet','jackson'), ('lee','albert'), ('latoya','jackson') ]

sorted_names=sorted( names, cmp=cust_cmp)


('lee', 'albert')
('janet', 'jackson')
('latoya', 'jackson')
('mahalia', 'jackson')
('moon', 'zappa')
Notes by Willem Moors. Generated on momo:/home/willem/sync/20151223_datamungingninja/pythonbook at 2019-07-31 19:22