[Numpy-discussion] Sorting objects with ndarrays

Friedrich Romstedt friedrichromstedt@gmail....
Sun Feb 28 08:01:18 CST 2010


> 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.

I also do not understand how to build an oder on such a thing at all,
maybe you can give a simple example?

>> 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.

Hmm, you could also replace numpy.greater and similar temporarily with
an with statement like:

# Everything as usual, comparing ndarrays results in ndarrays here.

with monkeypatched_operators:
    # Comparing ndarrays may result in scalars or what you need.
    pass  # Perform the sorting

# Everything as usual ...

Though that's maybe not threadsafe too.

I think I'm lacking knowledge of what you want to achieve.

Ahh, I think you want to order them like in a telephone dictionary?

Then you could use ndarray.flatten().tolist() to compare them using
usual Python semantics?

my 2 cents,
Friedrich


More information about the NumPy-Discussion mailing list