Replacing cmp with key for sorting

George Sakkis george.sakkis at gmail.com
Mon Nov 3 12:49:35 EST 2008


I want to sort sequences of strings lexicographically but those with
longer prefix should come earlier, e.g. for s = ['a', 'bc', 'bd',
'bcb', 'ba', 'ab'], the sorted sequence is ['ab', 'a', 'ba', 'bcb',
'bc', 'bd']. Currently I do it with:

s.sort(cmp=lambda x,y: 0 if x==y else
                                    -1 if x.startswith(y) else
                                    +1 if y.startswith(x) else
                                    cmp(x,y))

Can this be done with an equivalent key function instead of cmp ?

George



More information about the Python-list mailing list