如何获取lis中唯一值的计数

2024-06-11 14:46:44 发布

您现在位置:Python中文网/ 问答频道 /正文

给出一个列表: a=['ed'、'ed'、'ed'、'ash'、'ash'、'daph']

我想遍历这个列表,得到前两个最常用的名字。所以我应该期待一个结果['ed','ash']

[更新]

不用图书馆怎么办


Tags: 列表图书馆名字edashdaph
2条回答

^{}有一个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个最常见的元素(以及它们的多重性);然后列表理解会删除多重性,只删除原始列表中的项。你知道吗

尝试:

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

相关问题 更多 >