我有一个defaultdict
,然后转换成字典。现在我正在寻找一种方法来计算按值分组的项目。我的意思是:
dict = {1: [103], 2: [9], 3: [3, 4], 4: [103, 106], 10: [3, 4], 11: [1, 9], 28: [1]}
for key in dict.items():
print key
(1, [103])
(2, [9])
(3, [3, 4])
(4, [103, 106])
(10, [3, 4])
(11, [1, 9])
(28, [1])
item : total
{4 : 2, 106 : 1} ...
我该怎么做?
最佳答案
您可以使用 collections.Counter
计算值列表中每个元素出现的次数,像这样
>>> from collections import Counter
>>> Counter(value for values in d.itervalues() for value in values)
Counter({1: 2, 3: 2, 4: 2, 103: 2, 9: 2, 106: 1})
Counter
只是字典的子类。因此,您可以像使用任何其他词典一样使用它
值的扁平化可以用 itertools.chain.from_iterable
来完成, 像这样
>>> from collections import Counter
>>> from itertools import chain
>>> Counter(chain.from_iterable(d.itervalues()))
Counter({1: 2, 3: 2, 4: 2, 103: 2, 9: 2, 106: 1})
关于python - 计算 defaultdict 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30664449/