sorting list of complex numbers

Paul Rubin http
Tue Nov 18 11:27:03 CET 2008

Duncan Booth <duncan.booth at invalid.invalid> writes:
> 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)

That only goes so far though.  Suppose instead of complex numbers
you want to sort expressions, like:


treat those as parse trees in the obvious way.  You want to compare on
the root, and if the roots are equal, compare the left subtree, then
the right subtree, etc.  Do you REALLY want to sort over and over
all the way to the max depth of all the trees?

I don't understand what the purpose of was of getting rid of the cmp
arg.  It just seems to gratuitously make code hard to write.

Another thing that apparently broke was tuple destructuring in
function args.  You can no longer say

   def first((a,b)): return a
   def second((a,b)): return b

make getters for the first and second elements of a tuple.  Sure, you
could use operator.itemgetter for that example, but often you want to
parse out more complicated nested tuples.  I do that all the time with
Python 2.5 (typically in conjunction with itertools.groupby) but
if/when I downgrade to 3.0, a bunch of my code is going to break.

More information about the Python-list mailing list