Reputation: 1252
The standard way to sort a list a based on list b, is to zip them together and use sorted, like
sorted(zip(b,a))
However, if two elements in b are equal, it will automatically proceed to try to sort according to a, and that sometimes causes problems. Consider for example
import numpy as np
a=[np.array([4,5]),np.array([3,4])]
b=[1,1]
e=zip(b,a)
sorted(e)
this causes the error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
So when two elements in b are equal, it seems to proceed to sort according to a, but since a contains numpy arrays, the sorting algorithm complain when it tries to compare them.
Anyway, is this expected behaviour of sorted? In any case, I just want to sort according to b. If two elements are equal, the order does not matter. Any ideas on how to fix this without writing a sorting algorithm myself?
Upvotes: 1
Views: 126
Reputation: 214927
The error shows up because numpy.array
is not comparable in the sense of sorting, i.e. it doesn't return a True
or False
value (but another boolean array) when comparing two arrays, which is different from lists comparison.
If you only want to sort according to b
, provide a key function to sorted
:
sorted(e, key=lambda x: x[0])
# [(1, array([4, 5])), (1, array([3, 4]))]
Upvotes: 1