python每日一题公众号_Python每日一练0009

问题

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

解决方案

使用collections库中的Counter对象可以方便的求出现次数最多的前N个元素

直接使用most_common成员函数就好了,例如:

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'

]

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每日一练

你可能感兴趣的:(python每日一题公众号)