python找出序列中出现次数最多的元素之Counter对象
2017-07-12 14:11
806 查看
解决此类问题我们将用到collections模块中的Counter类,并直接调用Counter类的most_common()方法或得答案。
用下面的例子来讲解具体用法:
基本用法
增加计数
Counter对象的实用特性拓展,结合各种数学运算操作使用
用下面的例子来讲解具体用法:
基本用法
from collections import Counter #首先导入Counter类 lst=['this','is','a','test','just','a','test','you','shoud','believe','in','this','me','just','a','test','a','test','a','test'] #构建一个列表 word_count=Counter(lst) #首先对列表的元素进行一次统计 top_three=word_count.most_common(3) #调用most_common方法找出最多的元素 print(top_three) #输出结果[('test', 5), ('a', 5), ('just', 2)]
增加计数
morewords=['why','are','you','not','looking','at','my','eyes','this','really','nothing','just','a','pity'] #构建另一个列表 #手动增加 for word in morewords: word_count[word]+=1 #或者调用update方法直接增加计数,效果一样 #word_count.update(morewords) print(word_count) #Counter({'a': 6, 'test': 5, 'this': 3, 'just': 3, 'you': 2, 'why': 1, 'eyes': 1, 'is': 1, 'nothing': 1, 'looking': 1, 'me': 1, 'really': 1, 'shoud': 1, 'in': 1, 'not': 1, 'believe': 1, 'at': 1, 'pity': 1, 'my': 1, 'are': 1})
Counter对象的实用特性拓展,结合各种数学运算操作使用
a=Counter(lst) b=Counter(morewords) c=a+b #求两个结果的并集 print(c) #Counter({'a': 6, 'test': 5, 'this': 3, 'just': 3, 'you': 2, 'at': 1, 'why': 1, 'is': 1, 'looking': 1, 'me': 1, 'really': 1, 'shoud': 1, 'in': 1, 'eyes': 1, 'believe': 1, 'nothing': 1, 'pity': 1, 'my': 1, 'are': 1, 'not': 1}) print('----------------') d=a-b #求两个结果的差集 print(d) #Counter({'test': 5, 'a': 4, 'shoud': 1, 'in': 1, 'believe': 1, 'is': 1, 'me': 1, 'this': 1, 'just': 1})
相关文章推荐
- Python cookbook(数据结构与算法)找出序列中出现次数最多的元素算法示例
- python 找出序列中出现次数最多的元素方法。
- python 找出序列中出现次数最多的元素方法
- [PY3]——找出一个序列中出现次数最多的元素/collections.Counter 类的用法
- Python实用黑科技——找出序列里面出现次数最多的元素
- 利用Python找出序列中出现最多的元素示例代码
- java找出一个数组中出现次数最多的那个元素
- Python第三方库——Numpy_怎么得到向量中出现次数最多的元素值?
- java找出一个数组中出现次数最多且最大的那个元素
- java找出一个数组中出现次数最多的那个元素(用HashSet很新颖)
- python(dict字典相关知识以及小例子:生成一个列表,存放100个随机整数,找出出现次数最多的数字)
- java找出一个数组中出现次数最多的那个元素
- 找出数组里面元素出现次数最多的问题
- 输出列表中出现次数最多的元素 分类: python 2013-01-15 15:25 990人阅读 评论(0) 收藏
- 编写一个小程序,从标准输入读入一系列string对象,寻找连续重复出现的单词。程序应该找出满足一下条件的单词:该单词的后面紧接着再次出现自己本身。跟踪重复次数最多的单词及其重复次数,输出.
- python 2-3 如何统计序列中元素的出现频度--collections.Counter
- python【3】-统计序列中元素出现的次数(频度)
- java 找出n个元素数组中重复次数最多的数(假设出现次数大于n/2)
- 找出数组中出现次数最多的前k个元素[leetcode题]
- 找出数组里面元素出现次数最多的问题