2024-04-18 14:52:27 发布
网友
我是Python新手,我有一个简单的问题,比如我有一个项目列表:
['apple','red','apple','red','red','pear']
如何最简单地将列表项添加到字典中,并计算该项在列表中出现的次数。
所以对于上面的列表,我希望输出为:
{'apple': 2, 'red': 3, 'pear': 1}
>>> 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})
我喜欢:
counts = dict() for i in items: counts[i] = counts.get(i, 0) + 1
.get允许您在密钥不存在时指定默认值。
在2.7和3.1中,有专门的^{}dict用于此目的。
>>> from collections import Counter >>> Counter(['apple','red','apple','red','red','pear']) Counter({'red': 3, 'apple': 2, 'pear': 1})
我喜欢:
.get允许您在密钥不存在时指定默认值。
在2.7和3.1中,有专门的^{} dict用于此目的。
相关问题 更多 >
编程相关推荐