Python 如何获取列表中唯一值的计数
给出一个列表: a=['ed','ed','ed','ash','ash','daph'] 我想反复浏览一下这个列表,找出最常用的两个名字。所以我应该期待一个['ed','ash']的结果 [更新] 如何在不使用库的情况下执行此操作请尝试:Python 如何获取列表中唯一值的计数,python,Python,给出一个列表: a=['ed','ed','ed','ash','ash','daph'] 我想反复浏览一下这个列表,找出最常用的两个名字。所以我应该期待一个['ed','ash']的结果 [更新] 如何在不使用库的情况下执行此操作请尝试: >>> from collections import Counter >>> c = Counter(a) >>> c Counter({'ed': 3, 'ash': 2, 'daph': 1})
>>> 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']
有一种最常用的方法:
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)
我得到了两个最常见的元素(以及它们的多重性);然后列表理解会删除多重性,只删除原始列表中的项目。相等的元素是否总是彼此相邻?@EugeneSh。不,我只是这样做的,这样很容易理解,但是如果排序函数有助于提高效率,那么我们可以尝试:使用@e_mam106的可能副本集合模块是python标准库的一部分(因为很长时间了!)。它很难被称为“图书馆”。任何(合理地说是最新的)python发行版都将附带collections模块。