在Python列表中计算值频率的最有效方法是什么?
我想找一种快速有效的方法来计算Python中list
里每个项目出现的频率:
list = ['a','b','a','b', ......]
我希望能得到一个频率统计器,输出结果像这样:
[ ('a', 10),('b', 8) ...]
这些项目应该按出现频率从高到低排列,像上面那样。
1 个回答
33
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)]