Importing the Collections module

from collections import Counter
Copy the code

To generate an array

arr = [1.1.2.0.0.1.2.3]
print(arr)
Copy the code

Instantiate the Counter object with the array to be counted

counter = Counter(arr)
print(counter)
Copy the code

Will get

Counter({1: 3, 2: 2, 0: 2, 3: 1})
Copy the code

The Counter class also provides a method called MOST_common to turn a dictionary of count results into a list of count results in descending order

most_common_all = counter.most_common()
print(most_common_all)
# [(1, 3), (2, 2), (0, 2), (3, 1)]
Copy the code

You can also get the maximum n count result by passing in an argument

most_common_top1 = counter.most_common(1)
print(most_common_top1)
# "(1, 3)"
Copy the code