【发布时间】:2016-12-11 22:41:55
【问题描述】:
假设我有一个集合的字典:
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']}
但这似乎有点笨拙。有没有更简单的方法来做到这一点?
【问题讨论】:
-
已有答案here
-
寻找更好的方法来创建
inverted:inverted = {k: [] for k,v in Counter(chain(*DictofSets.values())).items() if v > 1}。至于最后的循环,我想不出另一种方式 atm 但我觉得不太笨拙。
标签: python python-3.x dictionary set