【问题标题】:How to get count of unique values in a list如何获取列表中唯一值的计数
【发布时间】:2017-10-12 02:25:05
【问题描述】:

给定一个列表: a = ['ed', 'ed', 'ed', 'ash', 'ash, 'daph']

我想遍历列表并获得前 2 个最常用的名称。所以我应该期待 ['ed', 'ash']

[更新]

如何在不使用库的情况下解决此问题

【问题讨论】:

标签: python


【解决方案1】:

collections.Counter 有一个most_common 方法:

from collections import Counter

a = ['ed', 'ed', 'ed', 'ash', 'ash', 'daph']

res = [item[0] for item in Counter(a).most_common(2)]

print(res)  # ['ed', 'ash']

most_common(2) 我得到了 2 个最常见的元素(以及它们的多样性);列表理解然后删除多重性并仅删除原始列表中的项目。

【讨论】:

  • @e_mam106 集合模块是 python 标准库的一部分(很久以来!)。它几乎不能称为“图书馆”。任何(最近的)python 发行版都将附带 collections 模块。
【解决方案2】:

尝试:

>>> from collections import Counter

>>> c = Counter(a)

>>> c
Counter({'ed': 3, 'ash': 2, 'daph': 1})

# Sort items based on occurrence using most_common()
>>> c.most_common()
[('ed', 3), ('ash', 2), ('daph', 1)]

# Get top 2 using most_common(2)
>>> [item[0] for item in c.most_common(2)]
['ed', 'ash']

# Get top 2 using sorted
>>> sorted(c, key=c.get, reverse=True)[:2]
['ed', 'ash']

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 2014-11-26
    • 2021-06-26
    • 2019-11-10
    • 1970-01-01
    • 2012-08-30
    相关资源
    最近更新 更多