python - 计算 defaultdict 中的项目

标签 python python-2.7 dictionary

我有一个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/

相关文章:

python - 映射 lambda 创建字典

python 将 beautifulsoup 输出转换为 dict/json

python - 为什么 Python 中的整数需要三倍的内存?

python-2.7 - 使用python将一系列ppm图像转换为视频

python - 根据python中列的条件更新行值

python - 从 JSON 数据访问数组中字段的值

image-processing - 使用 imagemagick/PIL 在 python 中的图像上添加文本

Python 列表到字典 - 没有值覆盖

python - 如何在数据库中存储实时聊天消息?

Python 装饰器确定方法的执行顺序