Python 字典排序奇怪的行为

问题描述 投票:0回答:1

我想根据多个标准对 python 字典进行排序,具体取决于其值的条件,例如:

d = {'27': 'good morning', '14': 'morning', '23': 'good afternoon', '25': 'amazing'}

priority_1 = 'good'
priority_2 = 'morning'
priority_3 = 'afternoon'
new_d = sorted(d.items(), key=lambda c: [(priority_1 and priority_2) in c[1], priority_3 in c[1]])

这给出了:

[('25', 'amazing'),
 ('23', 'good afternoon'),
 ('27', 'good morning'),
 ('14', 'morning')]

虽然我期望它会回来:

    [('25', 'amazing'),
     ('23', 'good afternoon'),
     ('14', 'morning'),
     ('27', 'good morning')]

更有趣的是,我认为写

priority_1 and priority_2 in c[1]
priority_2 and priority_1 in c[1]
没有什么不同,但事实证明我错了,因为当我将顺序更改为
priority_2 and priority_1 in c[1]
时,我得到了不同的结果。

我在文档中找不到关于与逻辑运算符一起使用时操作数顺序的影响的答案。

python python-3.x sorting
1个回答
0
投票

(priority_1 and priority_2) in c[1]
评估为首先检查
priority_1 and priority_2
,变成
True
。然后它检查
True
是否在字符串中,但事实并非如此。

© www.soinside.com 2019 - 2024. All rights reserved.