运用场景
有时候我们需要统计一个序列中出现最多或者次多的元素,或者是给你一段文字,这段文字中出现最多的词是什么,以及每个词出现的次数,这个在写代码的初级篇大家都会遇到。
一般的做法,我肯定会用一个字典做遍历,key 就是我们要处理的元素,然后value就是我们的统计结果。
但是这种一看就是轮子,所以我们就愉快的直接用吧。
Python专门设计了一个类来处理这个问题
下面就是这个类的具体的用法,假设我们有一个单词列表,我们想要找出那个单词出现的频率最高。
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'
]
from collections import Counter
word_counts = Counter(words)
# 出现频率最高的3个单词
top_three = word_counts.most_common(3)
print(top_three)
# Outputs [('eyes', 8), ('the', 5), ('look', 4)]
Reference
https://www.biaodianfu.com/python-list-value-count.html