George Sakkis <[EMAIL PROTECTED]> 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 -- http://mail.python.org/mailman/listinfo/python-list