我是Python的新手,我有一个简单的问题,说我有一个项目列表:['apple','red','apple','red','red','pear']将列表项添加到字典并计算该项目在列表中出现的次数的最简单方法是什么?因此,对于上面的列表,我希望输出为:{'apple': 2, 'red': 3, 'pear': 1}
3 回答

阿波罗的战车
TA贡献1862条经验 获得超6个赞
在2.7和3.1中Counter,为此目的有一个特殊的命令。
>>> from collections import Counter
>>> Counter(['apple','red','apple','red','red','pear'])
Counter({'red': 3, 'apple': 2, 'pear': 1})

函数式编程
TA贡献1807条经验 获得超9个赞
我喜欢:
counts = dict()
for i in items:
counts[i] = counts.get(i, 0) + 1
如果密钥不存在,.get允许您指定默认值。

人到中年有点甜
TA贡献1895条经验 获得超7个赞
>>> L = ['apple','red','apple','red','red','pear']
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in L:
... d[i] += 1
>>> d
defaultdict(<type 'int'>, {'pear': 1, 'apple': 2, 'red': 3})
添加回答
举报
0/150
提交
取消