Annoying behaviour of the != operator

David M. Cooke cookedm+news at physics.mcmaster.ca
Thu Jun 9 17:54:27 CEST 2005


Greg Ewing <greg at cosc.canterbury.ac.nz> writes:

> Rocco Moretti wrote:
>
>  > This gives the wacky world where
>> "[(1,2), (3,4)].sort()" works, whereas "[1+2j, 3+4j].sort()" doesn't.
>
> To solve that, I would suggest a fourth category of "arbitrary
> ordering", but that's probably Py3k material.

We've got that: use hash().
[1+2j, 3+4j].sort(key=hash)

Using the key= arg in sort means you can do other stuff easily of course:

by real part:
import operator
[1+2j, 3+4j].sort(key=operator.attrgetter('real'))

by size:
[1+2j, 3+4j].sort(key=abs)

and since .sort() is stable, for those numbers where the key is the
same, the order will stay the same.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list