如何“排序”python字典,使每个“值”都是一个数组?

2024-04-19 11:42:03 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,如果我的字典(或不管它叫什么)看起来像

itemList =
[
{
'attribute1': (1,2)
'attribute2': (3,4)
...
}
{ 
'attribute1': (5,6)
'attribute2': (7,8)
...
}
]

我试着按照attribute1的第二个数字来排序:

sorted(itemList, key=lambda x: ['attribute1'][1]

但这给了我一个错误

IndexError: list index out of range

我怎样才能解决这个问题?你知道吗


Tags: oflambdakeyindex字典排序错误数字
3条回答

应该是:

sorted(itemList, key=lambda x: x['attribute1'][1])

按照您的方式,它试图访问列表['attribute1']的第二个元素,但该元素不存在。你知道吗

你的lambda表达式没有任何意义: 实际上,您正在尝试访问并返回列表的第二个元素:['attribute1'],它显然只有一个元素!你知道吗

你应该写的是:

sorted(itemList, key=lambda x: x['attribute1'][1]
                               ^
                               |
             missing variable matching an element of the list

所以xitemList的一个项目。你知道吗

编辑:

As a follow up, I am still confused why ['attribute1'] has only one element? In my example, I have 'attribute1': (1,2), isn't that "2" the second element?

好吧,因为让您感到困惑的是,['attribute1']不是x['attribute1'],但它仍然是一个有效的python语法,即包含一个元素的未命名列表,字符串'attribute1'。你知道吗

正如您将x定义为listtuple,您希望使用[]操作符从tuple中提取一个值。但由于该运算符存在于列表中,因此当您访问['attribute1']之外的值时,它在语法上是正确的。但是因为['attribute1']只有一个元素,所以它在语义上是不正确的,并因此对你大喊大叫list index out of range!你知道吗

我不知道你在哪儿弄糊涂了。lambda表达式不是魔法,它严格等价于以下表达式:

def get_second_of_attribute1(x):
    return x['attribute1'][1]

sorted(itemList, key=get_second_of_attribute1)

这里,xsorted()给函数的参数,该函数定义为第一个参数key的每个项的itemList参数,用于进行比较,以便列表按排序返回。你知道吗

总之,lambda表达式,一般来说python编译器不会猜测您要做什么,它需要显式和清晰的指令。如果你告诉他出了什么事,他要么对你大喊大叫(如果不可能的话),要么真的这么做!你知道吗

例如,如果您在itemList中查找元组的第一个元素,那么您最终将没有错误,但排序返回一个未排序的列表,因为key函数总是返回相同的东西:'attribute1'。你知道吗

嗯!你知道吗

尝试:

sorted(itemList, key=lambda x: x['attribute1'][1]

相关问题 更多 >