简体   繁体   中英

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).

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.

Probably using the key parameter. Is this what you want?

import numpy as np
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(key=lambda x: x[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM