3 回答
TA贡献2036条经验 获得超8个赞
您可以取消嵌套 dict 的值并应用Counter.
>>> from collections import Counter
>>>
>>> d = {'key1':['apple', 'orange'], 'key2':['orange', 'pear']}
>>> Counter(v for sub in d.values() for v in sub)
Counter({'apple': 1, 'orange': 2, 'pear': 1})
如果您不喜欢嵌套生成器理解,可以使用itertools.chain.from_iterable.
>>> from itertools import chain
>>> Counter(chain.from_iterable(d.values()))
Counter({'apple': 1, 'orange': 2, 'pear': 1})
没有导入和传统循环,它看起来像这样:
>>> result = {}
>>> for sub in d.values():
...: for v in sub:
...: result[v] = result.get(v, 0) + 1
...:
>>> result
{'apple': 1, 'orange': 2, 'pear': 1}
TA贡献2037条经验 获得超6个赞
像这样的事情应该可以解决问题:
>>> from collections import Counter
>>> counts = Counter([item for sublist in your_dict.values() for item in sublist])
添加回答
举报