对列表进行排序,按受欢迎程度去重
可能重复的问题:
在Python中,我如何根据列表中某个元素的出现次数进行排序?
大家好,
我想找一个简单的方法来根据受欢迎程度对一个列表进行排序,然后去掉重复的元素。
比如,给定一个列表:
[8, 8, 1, 1, 5, 8, 9]
最后我想得到一个像下面这样的列表:
[8, 1, 5, 9]
2 个回答
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]
请查看 collections.Counter
的文档,里面有关于旧版本兼容实现的链接。
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]
不过,这个解决办法比较耗费资源(因为使用了 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)