计算Python列表中的值频率的最有效方法? [英] Most Efficient way to calculate Frequency of values in a Python list?

查看:98
本文介绍了计算Python列表中的值频率的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种快速有效的方法来计算python中list个项目的频率:

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.

推荐答案

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)]

这篇关于计算Python列表中的值频率的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆