Annoying behaviour of the != operator

Jp Calderone exarkun at divmod.com
Fri Jun 10 18:28:53 CEST 2005


On 10 Jun 2005 09:05:53 -0700, Dan Bishop <danb_83 at yahoo.com> wrote:
>Steven D'Aprano wrote:
>...
>> If you were to ask, "which is bigger, 1+2j or 3+4j?" then you
>> are asking a question about mathematical size. There is no unique answer
>> (although taking the absolute value must surely come close) and the
>> expression 1+2j > 3+4j is undefined.
>>
>> But if you ask "which should come first in a list, 1+2j or 3+4j?" then you
>> are asking about a completely different thing. The usual way of sorting
>> arbitrary chunks of data within a list is by dictionary order, and in
>> dictionary order 1+2j comes before 3+4j because 1 comes before 3.
>>
>> This suggests that perhaps sort needs a keyword argument "style", one of
>> "dictionary", "numeric" or "datetime", which would modify how sorting
>> would compare keys.
>>
>> Perhaps in Python 3.0.
>
>What's wrong with the Python 2.4 approach of
>
>>>> clist = [7+8j, 3+4j, 1+2j, 5+6j]
>>>> clist.sort(key=lambda z: (z.real, z.imag))
>>>> clist
>[(1+2j), (3+4j), (5+6j), (7+8j)]
>

It's not a general solution:

    >>> L = [1, 'hello', 2j]
    >>> L.sort(key=lambda x: (x.real, x.imag))
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 1, in <lambda>
    AttributeError: 'int' object has no attribute 'real'

Jp



More information about the Python-list mailing list