1

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()
1
  • Read the error...see what it says. It's pretty clear. If it isn't, google it. THEN ask the question. Commented Dec 13, 2015 at 1:46

2 Answers 2

1

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]))]
Sign up to request clarification or add additional context in comments.

4 Comments

Just a note: the author's 'list' is actually a tuple, which has no sort attribute.
@timgeb, The question title mentions list.
@falsetru Just change your answer to use the sorted builtin instead since it works for any container or iterable type.
@falsetru yes, I just figured the author does not know the difference to a tuple.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.