您的位置:首页 > 编程语言 > Python开发

python找出序列中出现次数最多的元素之Counter对象

2017-07-12 14:11 806 查看
解决此类问题我们将用到collections模块中的Counter类,并直接调用Counter类的most_common()方法或得答案。

用下面的例子来讲解具体用法:

基本用法

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})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐