dem*_*mos 16 python list frequency
我正在寻找一种快速有效的方法来计算listpython 中项目的频率:
list = ['a','b','a','b', ......]
Run Code Online (Sandbox Code Playgroud)
我想要一个频率计数器,它会给我一个像这样的输出:
[ ('a', 10),('b', 8) ...]
Run Code Online (Sandbox Code Playgroud)
如上所示,项目应按频率的降序排列.
Joh*_*ooy 32
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)])
Run Code Online (Sandbox Code Playgroud)
的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)]
Run Code Online (Sandbox Code Playgroud)