如何计算列表中的唯一值

时间:2017-05-12 17:19:51

标签: python

给出一个清单: a = [' ed'' ed'' ed',' ash',' ash,' daph& #39]

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

的结果

[更新]

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

2 个答案:

答案 0 :(得分:0)

尝试:

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

答案 1 :(得分:0)

collections.Countermost_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个最常见的元素(及其多样性); list-comprehension然后删除多重性,只删除原始列表中的项目。

相关问题