sorting list of complex numbers
Duncan Booth
duncan.booth at invalid.invalid
Sun Nov 9 09:54:27 EST 2008
skip at pobox.com wrote:
> I can sort by the real parts just fine:
>
> >>> lst.sort(key=lambda x: x.real)
> >>> pprint.pprint(lst)
> [2.6000000000000001j,
> 20j,
> (1+2.73j),
> (1+21j),
> (2+2.8600000000000003j),
> (2+22j),
> (3+2.9900000000000002j),
> (3+23j),
> (4+3.1200000000000001j),
> (4+24j),
> (5+3.25j),
> (5+25j),
> (6+26j),
> (6+3.3799999999999999j),
> (7+27j),
> (7+3.5100000000000002j),
> (8+28j),
> (8+3.6400000000000001j),
> (9+3.77j),
> (9+29j)]
>
> but how do I then do a secondary sort by the imaginary part, preserving the
> existing ordering on the real parts? Seems like I have to resort to a
> Schwartzian transform and map the complex numbers to tuples, sort that, then
> map them back. With the cmp key it would have been a fairly trivial task to
> define the desired compare-real-then-imag function.
>
> Is there a way to do this using just the key arg, no extra data structures?
Is a tuple an extra data structure?
>>> lst.sort(key=lambda x: (x.real,x.imag))
>>> pprint.pprint(lst)
[2.6000000000000001j,
20j,
(1+2.73j),
(1+21j),
(2+2.8600000000000003j),
(2+22j),
(3+2.9900000000000002j),
(3+23j),
(4+3.1200000000000001j),
(4+24j),
(5+3.25j),
(5+25j),
(6+3.3799999999999999j),
(6+26j),
(7+3.5100000000000002j),
(7+27j),
(8+3.6400000000000001j),
(8+28j),
(9+3.77j),
(9+29j)]
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)
>>> pprint.pprint(lst)
[2.6000000000000001j,
20j,
(1+2.73j),
(1+21j),
(2+2.8600000000000003j),
(2+22j),
(3+2.9900000000000002j),
(3+23j),
(4+3.1200000000000001j),
(4+24j),
(5+3.25j),
(5+25j),
(6+3.3799999999999999j),
(6+26j),
(7+3.5100000000000002j),
(7+27j),
(8+3.6400000000000001j),
(8+28j),
(9+3.77j),
(9+29j)]
>>>
More information about the Python-list
mailing list