How to sort a list? NOT a newbie question.
Grant Griffin
not.this at seebelow.org
Fri Sep 21 18:17:37 EDT 2001
In article <mailman.1001096306.20291.python-list at python.org>, "Tim says...
>
>[Grant Griffin]
>> ...
>> Cartesian_cmp = lambda a,b: (a.real != b.real) * cmp(a.real, b.real) + \
>> (a.real == b.real) * cmp(a.imag, b.imag)
>
>Why lambda? Surely
>
> def Cartesian_cmp(a, b):
> if a.real == b.real:
> return cmp(a.imag, b.imag)
> else:
> return cmp(a.real, b.real)
>
>is clearer.
Like I said, I used lambda just for fun. Also, I've been polishing my lambda
skills lately to make it easier to sort dictionaries by value <wink>.
>Simpler is
>
> Cartesian_cmp = lambda a, b: cmp((a.real, a.imag), (b.real, b.imag))
>
>That is, sequences in Python are compared lexicographically, and tuples are
>a sequence type; you don't have to fake lexicographic comparison by hand.
Cool!--I hadn't thought of that!
I guess it's axiomatic that a one-liner that fits on one line is much better
than a one-liner that doesn't.
But waitaminute! Are there two ways to do it?--or are they just not obvious?
>+ Python used to compare complex numbers that way.
>
>+ For technical implementation reasons, it used to be impossible to
> raise an exception from a comparison function. That's the real reason
> Python defined comparison on any pair of objects of builtin types:
> it had no choice.
Even so, I think it's a good idea.
...
>+ Eventually, it became possible to raise exceptions from comparisons,
> and, later, "rich comparisons" added the ability to know which
> specific comparison was desired. After both of those were in place,
> Guido was keen to allow complex comparisons only of the == and !=
> flavors.
Don't tell him, then, how my cold little DSP heart warmed to see that list
sorted in magnitude/phase order.
In all fairness, though, I've never had a need to sort a list of complex
numbers.
dictionaries-by-value-is-another-story-<wink>-ly y'rs,
=g2
_____________________________________________________________________
Grant R. Griffin g2 at dspguru.com
Publisher of dspGuru http://www.dspguru.com
Iowegian International Corporation http://www.iowegian.com
More information about the Python-list
mailing list