Skip to main content
 首页 » 编程设计

python之测试字典键是否存在的条件始终为 False

2025年02月15日8bonelee

我创建了一个使用两个字典的函数,curr_stats 和 weekly_result。如果 weekly_result 中有任何键不在 curr_stats 中,则该函数应该只打印 invalid_msg, 没有突变>curr_stats.

但是我的代码第 5 行的 if 语句似乎不起作用。它应该会触发下一个 if 语句,因此不会发生 curr_stats 的突变。

def update_standings(curr_stats, weekly_result): 
    invalid = 0 
    point_counter(weekly_result) 
    for team in weekly_result: 
        if team in curr_stats == False: 
            invalid = invalid + 1 
    if invalid > 0: 
        print(invalid_msg) 
    else: 
        for team in weekly_result: 
            curr_stats[team] = curr_stats[team] + weekly_result[team] 

请您参考如下方法:

在 Python 中,all comparisons have the same precedence , 包括 in . 发生的事情是 comparison chaining ,一种特殊形式,旨在测试数学课中的传递关系:

if x_min < x < x_max: 
    ... 

正如 Paweł Kordowski 在 his comment 中指出的那样,上面的比较链大部分等价于:

if x_min < x and x < x_max: 
    ... 

(有一个区别: “等效”代码可能评估 x两次,而比较链评估 x恰好一次。)

在你的例子中,比较链是:

if team in curr_stats == False: 
    ... 

...这(大部分)等同于:

if team in curr_stats and curr_stats == False: 
    ... 

只有在 curr_stats 时才成立包含 team 和 curr_stats是空的......这永远不会发生。

您的代码的问题是 == False --- 部分是因为它将比较变成了比较链,但主要是因为您从一开始就不需要它。 Python 提供了 not当您想要 bool 值的相反值时的关键字。 您的条件语句应为:

if team not in curr_stats: 
    invalid = invalid + 1 

最后一个建议: 通过去掉 invalid 可以使这个函数更短计数器并在无效时立即返回 team被发现。 (一旦您发现 weekly_result 是无效输入,您可能不关心它是否“甚至更多无效”。) 我也用过 dict.items 简化最后的for循环:

def update_standings(curr_stats, weekly_result): 
    point_counter(weekly_result) 
    for team in weekly_result: 
        if team not in curr_stats: 
            print(invalid_msg) 
            return 
    for team, result in weekly_result.items(): 
        curr_stats[team] += result