Most Efficient way to calculate Frequency of values in a Python list?

北战南征 提交于 2019-11-29 16:59:33

问题


I am looking for a fast and efficient way to calculate the frequency of list items in python:

list = ['a','b','a','b', ......]

I want a frequency counter which would give me an output like this:

 [ ('a', 10),('b', 8) ...]

The items should be arranged in descending order of frequency as shown above.


回答1:


Python2.7+

>>> from collections import Counter
>>> L=['a','b','a','b']
>>> print(Counter(L))
Counter({'a': 2, 'b': 2})
>>> print(Counter(L).items())
dict_items([('a', 2), ('b', 2)])

python2.5/2.6

>>> from collections import defaultdict
>>> L=['a','b','a','b']
>>> d=defaultdict(int)
>>> for item in L:
>>>     d[item]+=1
>>>     
>>> print d
defaultdict(<type 'int'>, {'a': 2, 'b': 2})
>>> print d.items()
[('a', 2), ('b', 2)]


来源:https://stackoverflow.com/questions/3172173/most-efficient-way-to-calculate-frequency-of-values-in-a-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!