在python中迭代地将list和check与next list结合起来

2024-06-18 11:12:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多本字典和一本基本字典。我需要遍历dictionary键,并且需要在每次迭代中检查现有键和新键,但是在每次迭代中,我需要将dictionary的所有以前的键组合起来,并使用当前dictionary键进行检查


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()中键的值)

新评分=(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)

如何实现动态列表数和迭代组合列表以检查键?你知道吗


Tags: keyinnewfordictionary字典keys分数
1条回答
网友
1楼 · 发布于 2024-06-18 11:12:20

使用提供的词典,即

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。你知道吗

相关问题 更多 >