gpt4 book ai didi

python - 如何在 python 中动态组合集合

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

我有一个字典列表,需要遍历它们并检查已经存在的键。我已经实现了一个 python 代码来手动计算分数,如下所示。在我的代码中,我在每次迭代中手动组合以前字典中的键。迭代将从 dict11 开始。

如何更改此代码以自动遍历动态数量的字典,以及在每次迭代中如何动态组合键?


dict10 = {'A': 1, 'C': 2}
dict11 = {'B': 3, 'C': 4}
dict12 = {'A': 5, 'E': 6, 'F': 7}
dict13 = {'G': 8, 'E': 9}

exist_score = 0

for key in dict11.keys() & dict10.keys():
exist_score += dict11[key]

for key in dict12.keys() & set(dict11.keys()).union(set(dict10.keys())):
exist_score += dict12[key]

for key in dict13.keys() & set(dict12.keys()).union(set(dict11.keys()).union(set(dict10.keys()))):
exist_score += dict13[key]

print(exist_score)

最佳答案

首先,您需要将它变成可以放入循环中的东西。 dict11dict12dict13 也会发生同样的事情:

# same definition for dict10, dict11, dict12, dict13

exist_score = 0
seen_keys = set(dict10.keys())

for key in dict11.keys():
if key in seen_keys:
exist_score += dict11[key]
seen_keys.update(dict11.keys())

for key in dict12.keys():
if key in seen_keys:
exist_score += dict12[key]
seen_keys.update(dict12.keys())

for key in dict13.keys():
if key in seen_keys:
exist_score += dict13[key]
seen_keys.update(dict13.keys())

这应该与您的脚本执行相同的操作。现在你可以把它放到一个循环中......

# same definition for dict10, dict11, dict12, dict13

exist_score = 0
seen_keys = set(dict10.keys())
other_dicts = [dict11, dict12, dict13]

for d in other_dicts:
for key in d.keys():
if key in seen_keys:
exist_score += d[key]
seen_keys.update(d.keys())

关于python - 如何在 python 中动态组合集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57190417/

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