使用字典计算列表中的项目数

2023-11-29

假设我有一个项目列表,例如:

['apple', 'red', 'apple', 'red', 'red', 'pear']

我想要一个字典来计算每个项目在列表中出现的次数。因此,对于上面的列表,结果应该是:

{'apple': 2, 'red': 3, 'pear': 1}

我怎样才能用Python简单地做到这一点?


If you are only interested in counting instances of a single element in a list, see How do I count the occurrences of a list item?.


在2.7和3.1中,有一个特殊的Counter (dict子类)用于此目的。

>>> from collections import Counter
>>> Counter(['apple','red','apple','red','red','pear'])
Counter({'red': 3, 'apple': 2, 'pear': 1})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用字典计算列表中的项目数 的相关文章

随机推荐