首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >计算Python列表中值频率的最有效方法是什么?

计算Python列表中值频率的最有效方法是什么?
EN

Stack Overflow用户
提问于 2010-07-04 01:04:36
回答 1查看 17.6K关注 0票数 17

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

list = ['a','b','a','b', ......]

我想要一个频率计数器,它会给我一个这样的输出:

 [ ('a', 10),('b', 8) ...]

这些项目应该按照如上所示的频率降序排列。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-07-04 01:12:41

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)]
票数 32
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3172173

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档