[Numpy-discussion] Sorting objects with ndarrays

Gael Varoquaux gael.varoquaux@normalesup....
Sun Feb 28 05:10:17 CST 2010


On Sun, Feb 28, 2010 at 01:05:15PM +0200, Pauli Virtanen wrote:
> su, 2010-02-28 kello 10:25 +0100, Gael Varoquaux kirjoitti:
> [clip]
> > The problem is that ndarrays cannot be compared. So I have tried to
> > override the 'cmp' in the 'sorted' function, however I am comparing
> > fairly complex objects, and I am having a hard time predicting wich
> > member of the object will contain the array. 

> I don't understand what "predicting which member of the object" means?
> Do you mean that in the array, you have classes that contain ndarrays as
> their attributes, and the classes have __cmp__ implemented?

Well, I might not have to compare ndarrays, but fairly arbitrary
structures (dictionnaries, classes and lists) as I am dealing with
semi-structured data coming from a stack of unorganised experimental
data. Python has some logic for comparing these structures by comparing
their members, but if these are ndarrays, I am back to my original
problem.

> If not, can you tell why

>         def xcmp(a, b):
>             a_nd = isinstance(a, ndarray)
>             b_nd = isinstance(b, ndarray)

>             if a_nd and b_nd:
>                 pass # compare ndarrays in some way
>             elif a_nd:
>                 return 1  # sort ndarrays first
>             elif b_nd:
>                 return -1 # sort ndarrays first
>             else:
>                 return cmp(a, b) # ordinary compare

> does not work?

Because I have things like lists of ndarrays, on which this fails. If I
could say: use recursively xcmp instead of cmp for this sort, it would
work, but the only way I can think of doing this is by monkey-patching
temporarily __builtins__.cmp, which I'd like to avoid, as it is not
thread safe.

Cheers,

Gaël


More information about the NumPy-Discussion mailing list