gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:11:28 25 4
gpt4 key购买 nike

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

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

关于python - 测试字典键是否存在的条件始终为 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42884411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com