假设我有一组命令:
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'])}
现在假设我想在一组以上的集合中找到set元素的键。
我所能做的最好的事情是:
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/