sort descending on a[1], ascending on a[0]

Erik Max Francis max at alcyone.com
Thu Oct 10 20:22:10 EDT 2002


"Manuel M. Garcia" wrote:

> What is everyones favorite way of sorting descending on a[1], and
> ascending on a[0]? (or however you wish, even changing this on
> the fly)
> 
> I am not a big fan of passing sort() a comparison function, but I
> don't see how I could use the Decorate - Sort - Undecorate (DSU)
> technique.

You can even use a lambda (or just a one-line function) that isn't
_totally_ horrible (I believe a similar pattern is mentioned in the
Cookbook):

>>> L = [(1, 'a'), (2, 'a'), (6, 'b'), (8, 'q'), (2, 'q'), (0, 'z')]
>>> L.sort(lambda x, y: cmp(y[1], x[1]) or cmp(x[0], y[0]))
>>> L
[(0, 'z'), (2, 'q'), (8, 'q'), (6, 'b'), (1, 'a'), (2, 'a')]

The use of or works since the second cmp will only be evaluated if the
first cmp is false, which means it must be zero, or that the values
match.  One can obviously also write cmp(y[1], x[1]) as -cmp(x[1],
y[1]), if one considers that more readable.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ They make it a desert and call it peace.
\__/ Tacitus
    WebVal / http://www.alcyone.com/pyos/webval/
 URL scanner, maintainer, and validator in Python.



More information about the Python-list mailing list