- 序列中出现次数最多的元素
- 问题
- 解决方案:
- collections.Counter 类就是专门为这类问题而设计的,它甚至有一个有用的most.common()方法 直接给了你答案。
-为了演示,先假设有一个单词列表并且想找出哪个单词出现频率最高。可以这样做:
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_counters = Counter(words)
top_three = word_counters.most_common(3)
print(top_three) # [('eyes', 8), ('the', 5), ('look', 4)]
- 讨论: 作为输入,Counter 对象可以接受任意的 hashable 序列对象。在底层实现上,一个Counter 对象 就是一个字典,将元素映射到他出现的次数上。比如:
print(word_counters["not"]) # 1
print(word_counters["eyes"]) # 8
morewords = ["why", "are", "you", "not", "looking", "in", "my", "eyes"]
for word in morewords:
word_counters[word] += 1
print(word_counters["eyes"]) # 9
word_counters.update(morewords) # 和上面的演示效果一样
- Counter 实例另一个特性是他们可以很容易的跟数学运算操作结合。比如:
a = Counter(words)
b = Counter(morewords)
c = a + b
print(c)
d = a - b
print(d)
- 毫无疑问,Counter 对象在几乎所有需要值班或者计数数据的场合是非常有用的工具,在解决这类问题的时候 应该有些选择它,而不是手动利用字典去实现。