Replacing cmp with key for sorting
Arnaud Delobelle
arnodel at googlemail.com
Mon Nov 3 13:44:19 EST 2008
George Sakkis <george.sakkis at gmail.com> writes:
> 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 ?
Here's an idea:
>>> sorted(s, key=lambda x: x+'z'*(3-len(s)))
['ab', 'a', 'ba', 'bcb', 'bc', 'bd']
The 3 above is the length of the longest string in the list
Here's another idea, probably more practical:
>>> sorted(s, key=lambda x: tuple(256-ord(l) for l in x), reverse=True)
['ab', 'a', 'ba', 'bcb', 'bc', 'bd']
HTH
--
Arnaud
More information about the Python-list
mailing list