1

I have a Python list of tuples:

vals = [(40.69, array([1.34, 1.516, 0.000135,....])), (213.69, array([0.34, 1.51256, 0.0110135,....])...]
vals.sort()

The first element in the tuple is a float and the second element is a numpy ndarray. There are 784 elements in the array.

I get ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() at vals.sort. I am trying to sort on the first element in the tuple itself. This code works when I use a smaller dataset that produces only 13 elements in the ndarray. I can't figure out why it should throw this particular error if the number of elements is more.

Can anyone please help me out?

SanjanaS801
  • 81
  • 2
  • 9
  • 6
    Well, odds are that two of the tuples share the same first element, so `list.sort()` has to compare the second elements of the two tuples to determine their relative order, at which point you encounter this numpy exception. If you only want to compare on the first element, use `vals.sort(key=lambda x: x[0])`. Looking for a dupe now. – senshin Feb 07 '16 at 04:57
  • This one has the same root cause as the issue you observe: [How to sort a list of objects in Python, based on an attribute of the objects?](http://stackoverflow.com/q/403421/) – senshin Feb 07 '16 at 04:59
  • 1
    That was indeed the issue. I didn't realize sort looks at the second element in case of a conflict. Thank you! I didn't spot a duplicate before but if you do, please let me know so I can remove it. – SanjanaS801 Feb 07 '16 at 05:00
  • 1
    Yes, `list.sort()` compares iterables elementwise, so if the first elements compare equal, it looks at the second, and if that fails, the third, and so forth. Please leave your question here rather than deleting it. It will help future users find solutions to their problems. – senshin Feb 07 '16 at 05:00
  • Sure. I've marked it as a duplicate. – SanjanaS801 Feb 07 '16 at 05:01

0 Answers0