如何从字典列表中移除子集字典

huangapple go评论129阅读模式
英文:

How to remove subset dictionaries from list of dictionaries

问题

我有一个字典列表,其中一些是子集:

l = [
    {'zero': 'zero', 'one': 'example', 'two': 'second'},
    {'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
    {'zero': 'zero'},
    {'zero': 'non-zero', 'one': 'example'}, ...
]

我想创建一个新的字典列表,其中不包含字典的子集。

res = [
    {'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
    {'zero': 'non-zero', 'one': 'example'}, ...
]
英文:

I have a list of dictionaries, and some of them are subsets:

l = [
    {'zero': 'zero', 'one': 'example', 'two': 'second'}, 
    {'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
    {'zero': 'zero'},
    {'zero': 'non-zero', 'one': 'example'}, ...
]

And I want to create a new list of dictionaries that do not contain a subset of dictionaries.

res = [
    {'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
    {{'zero': 'non-zero', 'one': 'example'}, ...
]

答案1

得分: 2

这段代码的目的是创建一个新的列表,该列表仅包含不是其他字典的子集的字典。

res = [
    d for d in l 
    if not any(set(d.items()).issubset(set(other.items()))
    for other in l if other != d)
    ]

print(res)

输出结果为:

[
    {'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
    {'zero': 'non-zero', 'one': 'example'}
]
英文:

This work around will create a new list that only contains dictionaries that are not subsets of any other dictionary in the list

res = [
    d for d in l 
    if not any(set(d.items()).issubset(set(other.items()))
    for other in l if other != d)
    ]

print(res)

Output:

[{'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
 {'zero': 'non-zero', 'one': 'example'}]

</details>



huangapple
  • 本文由 发表于 2023年1月9日 17:28:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定