collections.Counter 找出序列中出现次数最多的元素

问题:求以下序列元素出现次数前三的元素

import collections
words = [
    'look', 'into', 'my', 'look', 'into', 'my', 'eyes',
    'look', 'into', 'my', 'look', 'into', 'my', 'eyes', 'the', 'not',
    'my', 'my', 'look'
]
words_counts = collections.Counter(words)  # 在底层中,Counter是一个字典,在元素和它们出现的次数间做了映射
top_three = words_counts.most_common(3)  # 返回出现次数前三的元素
top_three
Out[4]: [('my', 6), ('look', 5), ('into', 4)]

# 可以给Counter对象提供任何可哈希的对象序列作为输入,在底层中,Counter是一个字典,在元素和它们出现的次数间做了映射
words_counts['my']
Out[5]: 6
words_counts['eyes']
Out[6]: 2
Counter对象操作的使用示例
# 1、实现简单的元素自增计数
morewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes']
for word in morewords:
    words_counts[word] += 1
words_counts['my']
Out[7]: 7

# 2、使用update()方法
words_counts.update(morewords)  # update()方法更改元素字典映射
words_counts.most_common(1)
Out[8]: [('my', 8)]

# 3、Counter对象可以同各种数学运算操作结合起来使用
a = collections.Counter(words)
b = collections.Counter(morewords)
a
Out[10]: Counter({'eyes': 2, 'into': 4, 'look': 5, 'my': 6, 'not': 1, 'the': 1})
b
Out[11]: 
Counter({'are': 1,
         'eyes': 1,
         'in': 1,
         'looking': 1,
         'my': 1,
         'not': 1,
         'why': 1,
         'you': 1})
a+b
Out[12]: 
Counter({'are': 1,
         'eyes': 3,
         'in': 1,
         'into': 4,
         'look': 5,
         'looking': 1,
         'my': 7,
         'not': 2,
         'the': 1,
         'why': 1,
         'you': 1})
a-b
Out[13]: Counter({'eyes': 1, 'into': 4, 'look': 5, 'my': 5, 'the': 1})
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值