gpt4 book ai didi

python - 反转多个集合的字典

转载 作者:行者123 更新时间:2023-12-01 03:29:27 26 4
gpt4 key购买 nike

假设我有一个集合字典:

DictofSets={
'Key1':set(['A', 'B', 'D', 'F']),
'Key2':set(['B', 'C', 'G']),
'Key3':set(['A', 'B', 'D', 'F']),
'Key4':set(['A', 'B', 'C', 'D', 'F']),
'Key5':set(['A', 'B', 'E', 'F'])}

现在假设我想查找出现在多个集合中的集合元素的键。

我能做的最好的事情是:

from collections import Counter

# first get counts of elements in excess of 1:
c=Counter()
for s in DictofSets.values():
c+=Counter(s)

# dict of lists for the keys if the set item occurs more than once
inverted={k:[] for k, v in c.items() if v>1}
for k in sorted(DictofSets):
for e in DictofSets[k]:
if e in inverted:
inverted[e].append(k)

它产生了我想要的东西:

>>> inverted
{'A': ['Key1', 'Key3', 'Key4', 'Key5'],
'C': ['Key2', 'Key4'],
'B': ['Key1', 'Key2', 'Key3', 'Key4', 'Key5'],
'D': ['Key1', 'Key3', 'Key4'],
'F': ['Key1', 'Key3', 'Key4', 'Key5']}

但是看起来有点笨拙。有没有更简单的方法来做到这一点?

最佳答案

我不认为OP的方法有什么问题。它可以更简洁地表达,但这并没有使它变得更好:

>>> import itertools as it
>>> c = Counter(it.chain.from_iterable(DictofSets.values()))
>>> {l: {k for k, s in DictofSets.items() if l in s} for l, n in c.items() if n > 1}
{'A': {'Key1', 'Key3', 'Key4', 'Key5'},
'B': {'Key1', 'Key2', 'Key3', 'Key4', 'Key5'},
'C': {'Key2', 'Key4'},
'D': {'Key1', 'Key3', 'Key4'},
'F': {'Key1', 'Key3', 'Key4', 'Key5'}}

关于python - 反转多个集合的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com