美文网首页
Python3 - 序列中出现次数最多的元素

Python3 - 序列中出现次数最多的元素

作者: 惑也 | 来源:发表于2018-12-16 12:05 被阅读27次

问题

怎样找出一个序列中出现次数最多的元素呢?

解决方案

Python内置的collections.Counter 类就是专门为这类问题设计的, 它有一个most_common() 方法,可以设置仅返回出现次数最多的前N个元素。比如:

from collections import Counter

words = [
    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
    'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
    'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
    'my', 'eyes', "you're", 'under'
]

word_counts = Counter(words)

print('单词出现的次数', word_counts)
print('出现次数最多的单词', word_counts.most_common(1))
print('出现次数最多的4个单词', word_counts.most_common(4))

每个单词出现的次数 Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, 'not': 1, "don't": 1, "you're": 1, 'under': 1})
出现次数最多的单词 [('eyes', 8)]
出现次数最多的前4个单词 [('eyes', 8), ('the', 5), ('look', 4), ('into', 3)]

讨论

Counter 对象可以接受由任意的hashable元素(不可变对象)构成的序列。 在底层实现上,一个 Counter 对象就是一个字典,将元素映射到它出现的次数上。比如:

print(word_counts['eyes'])
print(word_counts['look'])

8
4

使用 update() 方法,可以实现出现次数的累加,比如:

morewords = ['why','are','you','not','looking','in','my','eyes']

print(word_counts['eyes'])
word_counts.update(morewords)
print(word_counts['eyes'])

8
9

Counter 实例有一个鲜为人知的特性,它们可以进行数学运算的操作。比如:

a = Counter(words)
b = Counter(morewords)
print('a_count : ', a)
print('b_count : ', b)

print('a + b : ', a + b)
print('a - b : ', a - b)

a_count :  Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, 'not': 1, "don't": 1, "you're": 1, 'under': 1})
b_count :  Counter({'why': 1, 'are': 1, 'you': 1, 'not': 1, 'looking': 1, 'in': 1, 'my': 1, 'eyes': 1})
a + b :  Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2, 'around': 2, "don't": 1, "you're": 1, 'under': 1, 'why': 1, 'are': 1, 'you': 1, 'looking': 1, 'in': 1})
a - b :  Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2, "don't": 1, "you're": 1, 'under': 1})

毫无疑问, Counter 对象在几乎所有需要制表或者计数数据的场合是非常有用的工具。 在解决这类问题的时候应该优先选择它,而不是手动的利用字典去实现。

相关文章

网友评论

      本文标题:Python3 - 序列中出现次数最多的元素

      本文链接:https://www.haomeiwen.com/subject/gtwtkqtx.html