sorting list of complex numbers
steve at holdenweb.com
Mon Nov 10 03:29:27 CET 2008
skip at pobox.com wrote:
> Duncan> If you don't like the tuple then just do the two sorts separately:
> >>>> lst.sort(key=lambda x: x.imag)
> >>>> lst.sort(key=lambda x: x.real)
> I tried that. I could have sworn when I read through the output it hadn't
> retained the order of the real parts. Wait a minute... I sorted by real
> them by imag. So the trick is to sort by primary sort key last.
> Timeit suggests the single sort returning the real, imag tuples is faster
> than two sorts each on one field, as you might expect since many fewer calls
> to the key function are made.
Only half the number, of course. The advantage of the key function is
that each element requires only one call out to a Python function, and
the comparisons then take place using a C-coded comparison function.
But you knew that already, right?
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list