How to ignore case while doing most_common in Python's collections.Counter?

五迷三道 提交于 2020-01-03 23:03:26

问题


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.


回答1:


How about mapping it to str.lower?

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


来源:https://stackoverflow.com/questions/35184306/how-to-ignore-case-while-doing-most-common-in-pythons-collections-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!