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

解决此类问题我们将用到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})
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值