[英]Sort python dictionary based on a given column in an array
I have the following kind of dictionary 我有以下几种字典
import operator
my_dict = {'a':np.array((1,2)),'b':np.array((3,4))}
and I need to sorted based on the 1st column of the arrays. 并且我需要基于数组的第一列进行排序。 I can sort this other dictionary
我可以对这本其他字典进行排序
my_dict2 = {'a':np.array((1)),'b':np.array((3))}
using 运用
sorted(my_dict2.items(), key=operator.itemgetter(1),reverse=True)
but trying the same approach with my_dict, ie 但是用my_dict尝试相同的方法,即
sorted(my_dict.items(), key=operator.itemgetter(1),reverse=True)
throws the error message 引发错误信息
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I have tried to play with the argument in itemgetter, but I cannot order my_dict. 我尝试使用itemgetter中的参数,但无法订购my_dict。
I'm not exactly sure how to use operator to get subscripted values. 我不确定如何使用运算符获取下标值。 So what I did was this:
所以我要做的是:
sorted(my_dict.items(), key=lambda x: x[1][0],reverse=True)
Explanation: 说明:
x[1][0]
means you are taking the 1 and 3 out of ( 1 ,2) and ( 3 ,4). x[1][0]
表示你正在服用的1和3超过了(1,2)和(3,4)。
x[1][1]
means you are taking the 2 and 4 out of (1, 2 ) and (3, 4 ). x[1][1]
意味着你正在服用的2和4选自(1,2)和(3,4)。
x[0]
is the same as itemgetter(0)
which will sort by a and b, which is the keys of your dictionary. x[0]
与itemgetter(0)
相同,后者将按a和b排序,这是字典的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.