【发布时间】:2011-03-11 11:21:30
【问题描述】:
我正在寻找一种快速有效的方法来计算python中list项目的频率:
list = ['a','b','a','b', ......]
我想要一个频率计数器,它会给我这样的输出:
[ ('a', 10),('b', 8) ...]
项目应按频率降序排列,如上所示。
【问题讨论】:
我正在寻找一种快速有效的方法来计算python中list项目的频率:
list = ['a','b','a','b', ......]
我想要一个频率计数器,它会给我这样的输出:
[ ('a', 10),('b', 8) ...]
项目应按频率降序排列,如上所示。
【问题讨论】:
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)]
【讨论】:
Counter 不是最有效的方法;查看性能比较stackoverflow.com/questions/2522152/…