怎么找到序列中出现次数最多的元素呢?
collections.Counter类就是专门为这类问题设计,甚至有一个most_common直接给出答案
假设一个数字列表想找出哪个数字出现频率高
words = [1,1,1,1,2,3,3,3,4,4,5,6,7,8]
from collections import Counter
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
### 输出
[(1, 4), (3, 3), (4, 2)]
作为输入,Counter对象可以接受任意的由可哈希元素构成的序列对象,在底层实现上,一个Counter对象就是一个字典,将元素映射到它出现的次数上。比如:
word_counts[1]
word_counts[2]
### 输出
4
1