Dave
Dave

Reputation: 35

Sort list of number and array?

So I create this list of tuples where each tuple consists of an int and an array.

a = ((1, array([1,2,3])), (4, array([1,3,3])), (2, array([1,3,2]))) 

I want to sort the list so that the list is ordered from increasing int order.

ie.

a = ((1, array([1,2,3])), (2, array([1,3,2])), (4, array([1,3,3]))) 

I tried using

a.sort() 

which from the article I was reading should have sorted it how I want to but it returned the error

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Upvotes: 1

Views: 97

Answers (2)

timgeb
timgeb

Reputation: 78690

You can tell sorted to sort by the first element using a lambda expression:

>>> from numpy import array
>>> a = ((1, array([1,2,3])), (4, array([1,3,3])), (2, array([1,3,2])))
>>> a = tuple(sorted(a, key=lambda x: x[0]))
>>> a
((1, array([1, 2, 3])), (2, array([1, 3, 2])), (4, array([1, 3, 3]))

Note that a is a tuple and thus immutable. That's why I'm casting the return value of sorted to a tuple and reassign a.

Upvotes: 1

falsetru
falsetru

Reputation: 369064

Explicitly specify key function argument, so that only the first item; to make the int object is used as sort key:

>>> a = [(1, array([1,2,3])), (2, array([1,3,2])), (4, array([1,3,3]))]
>>> a.sort(key=lambda x: x[0])
>>> a
[(1, array([1, 2, 3])), (2, array([1, 3, 2])), (4, array([1, 3, 3]))]

Upvotes: 1

Related Questions