问题
怎样找出一个序列中出现次数最多的元素?
解决方案
使用collections
库中的Counter
对象可以方便的求出现次数最多的前N个元素
直接使用most_common
成员函数就好了,例如:
from collections import Counterwords = [ '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']counter = Counter(words)print(counter.most_common(1))复制代码
输出
[('eyes', 8)]复制代码
讨论
Counter
对象是dict
的子类,事实上内部存储也是按照k-v字典存储的,这里的v就是次数,所以Counter
对象支持dict
对象的所有操作
每一个Counter
对象初始化可以接受可迭代对象(iterable)、字典、关键字参数
>>> c = Counter() # a new, empty counter>>> c = Counter('gallahad') # a new counter from an iterable>>> c = Counter({ 'red': 4, 'blue': 2}) # a new counter from a mapping>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args复制代码
此外,Counter
对象还支持数学操作
>>> c = Counter(a=3, b=1)>>> d = Counter(a=1, b=2)>>> c + d # add two counters together: c[x] + d[x]Counter({ 'a': 4, 'b': 3})>>> c - d # subtract (keeping only positive counts)Counter({ 'a': 2})>>> c & d # intersection: min(c[x], d[x]) Counter({ 'a': 1, 'b': 1})>>> c | d # union: max(c[x], d[x])Counter({ 'a': 3, 'b': 2})复制代码
所以在遇到跟计数有关的问题时,不妨首先考虑一下Counter
对象
来源
Python Cookbook
关注
欢迎关注我的微信公众号:python每日一练