简体   繁体   English

如何对包含 numpy 数组的元组列表进行排序?

[英]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 ).如您所见,我有一个元组列表 ( ls )。 The first element of each tuple is a float number.每个元组的第一个元素是一个浮点数。 I try to sort the list by ls.sort() .我尝试通过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.在这种情况下,python 尝试使用元组的第二个元素来整理元组,但它不起作用,因为在元组中的第二个位置我有 numpy 数组。

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要么告诉 python 只对第一项进行排序

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

Or convert the whole thing to a structured numpy array and ask numpy to sort it或将整个事物转换为结构化的 numpy 数组并要求 numpy 对其进行排序

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.可能使用 key 参数。 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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