我有多个词典和一个基础词典。我需要迭代字典键,并且需要在每次迭代中检查现有键和新键,但在每次迭代中,我需要组合字典的所有先前键并检查当前字典键,例如
dict10 = {'A':1, 'C':2} #base dictionary
dict11 = {'B':3, 'C':4}
dict12 = {'A':5, 'E':6, 'F':7}
这里是计算过程
Exist_Score = (dict11.keys() & dict10.keys() 中键的值) + (dict12.keys() & (dict11.keys() + dict10.keys()) 中键的值
New_score = (dict11.keys() 中的键值 - dict10.keys()) + (dict12.keys() 中的键值 - (dict11.keys() + dict10.keys()))
我手动计算分数的方法
exist_score = 0
new_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 dict11.keys() - dict10.keys():
new_score += dict11[key]
for key in dict12.keys() - set(dict11.keys()).union(set(dict10.keys())):
new_score += dict12[key]
print(exist_score)
print(new_score)
对于给定的示例,分数将
存在得分 = 4 + 5
新分数 = 3 + (6 + 7)
如何实现动态数量的列表并迭代组合列表以检查键?
最佳答案
使用提供的字典,即
dict10 = {'A':1, 'C':2} #base dictionary
dict11 = {'B':3, 'C':4}
dict12 = {'A':5, 'E':6, 'F':7}
我们找到与基础字典相同的键和不在基础字典中的键,然后使用某些组合字典中的键计算分数:
# Combine all three dictionaries into one
dict_combine = dict(dict10, **dict(dict11, **dict12))
# Find keys that are the same with the base dictionary
keys_same = (dict10.keys() & dict11.keys()) | (dict10.keys() & dict12.keys())
# Find keys that are not in the base dictionary
keys_new = dict10.keys() ^ dict11.keys() ^ dict12.keys()
# Calculate scores
exist_score = sum([dict_combine[key] for key in keys_same])
new_score = sum([dict_combine[key] for key in keys_new])
现在,分数符合我们的预期:
>> exist_score
9
>> new_score
16
可以根据需要扩展代码以支持更多词典。
<小时/>编辑:
如果非基本字典不一定具有唯一的键(即它们可能彼此共享相同的键),您可以根据您提供的更新代码使用此功能:
def get_scores(base_dict, *new_dicts):
# Initialize scores
exist_score = 0
new_score = 0
# Iterate through non-base dictionaries
for i, i_dict in enumerate(new_dicts):
# Get base dictionary keys and find unions
keys = base_dict.keys()
for j in range(i):
keys = keys | new_dicts[j].keys()
# Find keys for existing score and new score
keys_same = i_dict.keys() & keys
keys_new = i_dict.keys() - keys
# Update scores
exist_score += sum([i_dict[key] for key in keys_same])
new_score += sum([i_dict[key] for key in keys_new])
# Return scores as tuple
return exist_score, new_score
现在,当我使用您的词典运行它时,我得到以下结果:
>> exist_score, new_score = get_scores(dict10, dict11, dict12)
>> exist_score
9
>> new_score
16
这将适用于动态数量的字典,在函数头中使用 *args
表示法。请参阅use of *args and **kwargs .
关于python - 迭代地组合列表并检查Python中的下一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57189301/