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

Conditional that tests for a dictionary key's presence is always False

我创建了一个使用两个字典的函数,curr_statsweekly_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,一种旨在测试传递关系的特殊形式,例如数学 class:

if x_min < x < x_max:
    ...

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

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

(有一处不同: "equivalent" 代码可能会评估 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 关键字,当您需要布尔值的对立面时。 您的条件语句应为:

if team not in curr_stats:
    invalid = invalid + 1

最后一个建议: 通过删除 invalid 计数器并在发现无效 team 时立即返回,可以使此函数更短。 (一旦你发现 weekly_result 是无效输入,你可能不关心它是否“even more invalid”。) 我还使用 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