列出一个列表,按人气排序,然后删除重复项

Ric*_*itt 6 python

可能重复:
在python中,如何在列表中出现最高的某些内容,并以这种方式对其进行排序?

大家好,

我正在寻找一种简单的方法来按人气排序列表,然后删除重复的元素.

例如,给出一个列表:

[8, 8, 1, 1, 5, 8, 9]
Run Code Online (Sandbox Code Playgroud)

然后我会得到如下列表:

[8, 1, 5, 9]
Run Code Online (Sandbox Code Playgroud)

Sil*_*ost 13

>>> lst = [1, 1, 3, 3, 5, 1, 9]
>>> from collections import Counter
>>> c = Counter(lst)
>>> [i for i, j in c.most_common()]
[1, 3, 5, 9]
Run Code Online (Sandbox Code Playgroud)

请参阅collections.Counterdocs以获取与旧版本兼容的实现的链接.

  • 你应该提到`Counter`仅适用于Python 2.7+.这是pre 2.7的实现:http://code.activestate.com/recipes/576611/(或者只能使用普通循环和dict;)) (2认同)

eum*_*iro 12

@SilentGhost为Python 2.7+提供了出色的解决方案.2.6及更早版本的相对简单的解决方案:

a = [8, 8, 1, 1, 5, 8, 9]

popularity = sorted(set(a), key=lambda x: -a.count(x))

[8, 1, 5, 9]
Run Code Online (Sandbox Code Playgroud)

然而,该解决方案昂贵(因为count).

这里有另一个更好的临时字典解决方案:

a = [8, 8, 1, 1, 5, 8, 9]
d = {}
for i in a:
    d[i] = d.get(i, 0) + 1
popularity = sorted(d, key=d.get, reverse=True)
Run Code Online (Sandbox Code Playgroud)

  • 这对于大型列表来说非常昂贵. (5认同)