A simple implementation of Python sorting according to the number of occurrences of elements in the list

I didn’t know how to sort according to the number of occurrences of elements in the list before. There is a simpler implementation in the numpy package, but I have been trying to figure out how to do it in the list (referring to a simple method), until today I found a counter called function

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]

The Counter method will return a dictionary, the key is the value of the element (equivalent to a collection), and the value is the number of occurrences of this element.

Guess you like

Origin blog.csdn.net/qq_62861466/article/details/127581468