Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of tuples that contain numpy array?

First, this is the code that does not work:

ls = [(1.0,np.array([3.0, 4.0])), (1.0,np.array([3.0, 4.1])), (3.0,np.array([2.0, 1.0]))]
ls.sort()

As you can see, I have a list of tuples (ls). The first element of each tuple is a float number. I try to sort the list by ls.sort(). In most of the cases it works well. However, sometimes (like in the example above) I have tuples with the same value of their first element. In this case the python try to use the second element of the tuple to sort out the tuples and it does not work because on the second place in the tuple I have numpy array.

How can I sort my list by ignoring the second elements of the tuples? If the first element is the same, I do not care about the ordering (it can be original ordering, or random).

like image 590
Roman Avatar asked Nov 15 '25 22:11

Roman


1 Answers

Either tell python to sort only on the first item

sorted(ls, key=lambda t: t[0])

Or convert the whole thing to a structured numpy array and ask numpy to sort it

ls_arr = np.array(ls, dtype=[('my_val', float), ('my_arr', float, 2)])
ls_arr.sort()

This second option only works if the arrays are always the same length.

like image 139
Eric Avatar answered Nov 18 '25 13:11

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!