Python 根据list中元素出现次数进行排序的简单实现

之前一直不太清楚怎么根据list中元素出现次数进行排序,numpy包中有更简单的实现,但是我一直想搞清楚怎么在list中完成(指用简便方法),直到今天发现了一个叫counter的函数

from collections import Counter
alist=[1,2,3,4,5,4,5,6,6,7,5,5,5,6,7,11,13,49,56,4]
count=Counter(alist)
alist.sort(key=lambda x :count[x],reverse=True)
print(alist)

输出结果为:
[5, 5, 5, 5, 5, 4, 4, 4, 6, 6, 6, 7, 7, 1, 2, 3, 11, 13, 49, 56]

Counter方法会返回一个字典,键为元素的值(相当于集合),值为这个元素出现的次数。

猜你喜欢

转载自blog.csdn.net/qq_62861466/article/details/127581468