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})
    原文作者:cook__
    原文地址: https://www.jianshu.com/p/2763f3515444
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞