Replacing cmp with key for sorting

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Nov 3 16:40:15 EST 2008


George Sakkis:
> but I guess there's not much more room for improvement.

That's nonsense, Python is a high level language, so there's nearly
always room for improvement (even in programs written in assembly you
can generally find faster solutions).
If speed is what you look for, and your strings are ASCII then this is
much faster:

tab = "".join(map(chr, xrange(256)))[::-1]
s.sort(key=lambda x: x.translate(tab), reverse=True)

Bye,
bearophile



More information about the Python-list mailing list