sorting list of complex numbers
tjreedy at udel.edu
Sun Nov 9 19:16:47 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.
This is called radix sorting. It requires that the sort be order
preserving, that it preserve the order of items with equal keys.
It is an old technique. It was used, for instance, to sort punched
cards on a card sorter that sorted cards on one columm at a time. One
had to be careful to properly remove and combine the cards after each
pass; make one mistake and start over. I once helped someone sort 1000s
of student record cards by 6- or 7-digit id.
Terry Jan Reedy
More information about the Python-list