如何在Python的集合中执行most

编程入门 行业动态 更新时间:2024-10-21 03:02:28
如何在Python的集合中执行most_common时忽略大小写。计数器?(How to ignore case while doing most_common in Python's collections.Counter?)

我正在尝试使用collections模块中的most_common迭代中元素的出现次数。

>>> 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'功能,以便我们可以获得所需的输出。

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)]

But what I expect is,

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

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

最满意答案

把它映射到str.lower怎么str.lower ?

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

How about mapping it to str.lower?

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

更多推荐

本文发布于:2023-07-17 07:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1141134.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!