How to sort a list? NOT a newbie question.
Skip Montanaro
skip at pobox.com
Mon Sep 17 11:08:39 EDT 2001
Michael> For the particular problem I was working on, it was simple to
Michael> find a workaround that was only slightly awkward. I don't have
Michael> any idea how to address the case shown above. Admittedly, it
Michael> is largely a rhetorical question, but what do people think is
Michael> the "one obvious way" to sort such a list? The goal is an
Michael> "arbitrary but deterministic" sort, much like with other
Michael> heterogeneous lists.
Seems to me that you need to convert complex numbers to reals for
comparison. That can be done a number of ways. Some that come immediately
to mind include:
* compare them as tuples, e.g., compare 1+2j as (1,2)
* ignore either the real or imaginary part
* compare them using magnitudes
Which you choose will depend on your application.
Here's an example of ignoring the imaginary part:
def _cmp(x,y):
if hasattr(x, "real"):
x = x.real
if hasattr(y, "real"):
y = y.real
return cmp(x,y)
l2 = [1, 1j, [1,'1j']]
l2.sort(_cmp)
print l2
--
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/
More information about the Python-list
mailing list