在Python的collections.Counter中执行most_common时如何忽略大小写? [英] How to ignore case while doing most_common in Python's collections.Counter?

查看:350
本文介绍了在Python的collections.Counter中执行most_common时如何忽略大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用collections模块中的most_common来计算可迭代元素中元素的出现次数.

I'm trying to count the number of occurrences of an element in an iterable using most_common in the collections module.

>>> names = ['Ash', 'ash', 'Aish', 'aish', 'Juicy', 'juicy']
>>> Counter(names).most_common(3)
[('Juicy', 1), ('juicy', 1), ('ash', 1)]

但是我期望的是

[('juicy', 2), ('ash', 2), ('aish', 2)]

是否存在"pythonic"方式/技巧来合并'ignore-case'功能,以便我们获得所需的输出.

Is there a "pythonic" way/trick to incorporate the 'ignore-case' functionality , so that we can get the desired output.

推荐答案

如何将其映射到str.lower?

>>> Counter(map(str.lower, names)).most_common(3)
[('juicy', 2), ('aish', 2), ('ash', 2)]

这篇关于在Python的collections.Counter中执行most_common时如何忽略大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆