简体   繁体   English

最有效的方法来计算Python列表中的值的频率?

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

I am looking for a fast and efficient way to calculate the frequency of list items in python: 我正在寻找一种快速有效的方法来计算python中list项的频率:

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. 如上所示,项目应按频率的降序排列。

Python2.7+ 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 的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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM