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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值