首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我有两个列表,我想合并它们,答案应该如下所示

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

Stack Overflow用户
提问于 2021-09-20 03:14:56
回答 5查看 101关注 0票数 2

我有两份字典清单,我想把它们合并。当字典出现在两个列表中时,我想在字典中添加一个“置信度”键,以反映词典在两个列表中都存在。

列表-1

代码语言:javascript
复制
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

代码语言:javascript
复制
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'}
]

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

代码语言:javascript
复制
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)

输出应该像那样

代码语言:javascript
复制
[
    {'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'}
]
EN

回答 5

Stack Overflow用户

发布于 2021-09-28 10:31:23

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将是您的结果

票数 1
EN

Stack Overflow用户

发布于 2021-09-28 10:47:27

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

代码语言:javascript
复制
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)
票数 1
EN

Stack Overflow用户

发布于 2021-09-28 10:59:26

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

代码语言:javascript
复制
# 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)]

将导致:

代码语言:javascript
复制
[{'confidence': 1, 'key': 'a'},
 {'key': 'b'},
 {'key': 'd'},
 {'key': 'c'},
 {'key': 'e'}]

注意,元素顺序将随着它们通过set而发生变化。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69248732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档