我有一个字典列表,需要遍历它们并检查已经存在的键。我已经实现了一个 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)
首先,您需要将它变成可以放入循环中的东西。 dict11
、dict12
和 dict13
也会发生同样的事情:
# 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())
我是一名优秀的程序员,十分优秀!