【问题标题】:How to ignore case while doing most_common in Python's collections.Counter?在 Python collections.Counter 中执行 most_common 时如何忽略大小写?
【发布时间】:2018-01-10 05:03:09
【问题描述】:

我正在尝试使用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' 功能,以便我们获得所需的输出。

【问题讨论】:

    标签: python string python-3.x list python-collections


    【解决方案1】:

    将其映射到str.lower 怎么样?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多