我有两个列表,我想合并它们,答案应该如下

2024-06-17 16:22:54 发布

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

我有两个字典列表,我想合并它们。当两个列表中都有词典时,我想为词典添加一个“信心”键,以反映词典在两个列表中都存在

列表-1

lst1 = [
    {'key': 'data_collected.service_data'},
    {'key': 'gdpr.gdpr_compliance'},
    {'key': 'disclosure_of_information.purpose_of_disclosure'},
    {'key': 'opt_out.choice_of_opt_out'}
]

列表2

lst2 = [
    {'key': 'child_data_protection.parent_guardian_consent'},
    {'key': 'ccpa.ccpa_compliance'},
    {'key': 'disclosure_of_information.purpose_of_disclosure'},
    {'key': 'opt_out.choice_of_opt_out'}
]

当我在代码下面运行时,我没有得到正确的输出

res = []
for x in lst1:
    for y in lst2:
        if x["key"] == y["key"]:
            if x not in res and y not in res:
                res.append({"key": x["key"], "confidence": 1})
        else:
            if x not in res and y not in res:
                res.append(x)
                res.append(y)

print(res)

输出应该是这样的

[
    {'key': 'data_collected.service_data'},
    {'key': 'gdpr.gdpr_compliance'},
    {
        'key': 'disclosure_of_information.purpose_of_disclosure',
        'confidence': 1
    },
    {
        'key': 'opt_out.choice_of_opt_out',
        'confidence': 1
    },
    {'key': 'child_data_protection.parent_guardian_consent'},
    {'key': 'ccpa.ccpa_compliance'}
]

Tags: ofkeyin列表datainformationnotres
3条回答

您可以使用set comprehension收集列表中每个字典的“关键”元素。然后可以循环遍历所有键,并检查两个列表中是否都有一个键

keys_1 = {d["key"] for d in lst1}
keys_2 = {d["key"] for d in lst2}

output = []
for k in keys_1 | keys_2:
    d = {"key": k}
    if k in keys_1 and k in keys_2:
        d["confidence"] = 1
    output.append(d)

可以使用set上的intersectionsymmetric_difference函数完全避免原始循环:

# Shortened key names for brevity
a = [{"key": "a"}, {"key": "b"}, {"key": "c"}]
b = [{"key": "a"}, {"key": "d"}, {"key": "e"}]

# Turn both lists into sets
a_keys = {entry["key"] for entry in a}
b_keys = {entry["key"] for entry in b}

# Add elements that are in both sets with confidence set to 1
result = [{"key": key, "confidence": 1} for key in a_keys.intersection(b_keys)]
# Add elements that are not in both sets
result += [{"key": key} for key in a_keys.symmetric_difference(b_keys)]

将导致:

[{'confidence': 1, 'key': 'a'},
 {'key': 'b'},
 {'key': 'd'},
 {'key': 'c'},
 {'key': 'e'}]

请注意,当元素通过set时,元素顺序将发生变化

lst1.extend(i for i in (i if i not in lst1 else lst1[lst1.index(i)].update({'confidence': 1}) for i in lst2) if i is not None)

lst1将是您的结果

相关问题 更多 >