假设我有一个项目列表,例如:
['apple', 'red', 'apple', 'red', 'red', 'pear']
我想要一个字典来计算每个项目在列表中出现的次数。所以对于上面的列表,结果应该是:
{'apple': 2, 'red': 3, 'pear': 1}
我怎样才能在 Python 中简单地做到这一点?
如果您只想计算列表中单个元素的实例,请参阅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})
关于python - 使用字典计算列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3496518/