Ordering python sets

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Oct 27 13:04:04 EDT 2008


Glenn Linderman:

> how does one create a key that corresponds to ascending integer followed by descending character string?

(Others may have already answered you because Google groups is very
slow.)

>>> seq = [(10, "abb"), (5, "zul"), (5, "hal"), (2, "of")]
>>> sorted(seq, key=lambda (n,s): (-n, s), reverse=True)
[(2, 'of'), (5, 'zul'), (5, 'hal'), (10, 'abb')]

A little harder question is how to create a key that corresponds to
ascending string followed by descending string?

To do that you can sort the data two times, relying on the stable
nature of the Python sort.

Another (silly?) solution may be to invent a "negate" function for
strings too:

>>> strneg = lambda txt: txt.translate(itable)
>>> itable = "".join(chr(i) for i in xrange(255, -1, -1))
>>> pairs = [('al', 'boo'), ('zul', 'ao'), ('al', 'den'), ('zul', 'o')]
>>> sorted(pairs, key=lambda (s1,s2): (s1, strneg(s2)))
[('al', 'den'), ('al', 'boo'), ('zul', 'o'), ('zul', 'ao')]

Bye,
bearophile



More information about the Python-list mailing list