Python combat from entry to the master speak the fifth - most elements appear in a sequence of 3 Data Structures and Algorithms

How to find the serial number of times it appears most of the elements?

collections.Counter class is specifically designed for this type of problem, and even a direct answer most_common

Suppose a list of numbers want to find out which numbers appear high frequency

words = [1,1,1,1,2,3,3,3,4,4,5,6,7,8]
from collections import Counter
word_counts = Counter(words)

top_three = word_counts.most_common(3)
print(top_three)

### 输出
[(1, 4), (3, 3), (4, 2)]

Target sequences, consisting of the hash element as input, an arbitrary object can accept Counter, on the underlying implementation, a Counter object is a dictionary, the elements map to the number of times it appears. such as:

word_counts[1]
word_counts[2]

### 输出
4
1

 

Published 334 original articles · won praise 170 · views 500 000 +

Guess you like

Origin blog.csdn.net/qq_32146369/article/details/104209441