Usage analysis of counter class in Python

Usage analysis of counter class in Python

I saw this class while reading the code recently, so I came to learn to record
"stay hungry, stay young"

The Counter class is a subclass of the dict class. To call it, you need to use the following statement:

from collection import Counter

It can be regarded as a special dictionary to facilitate our counting operation. Key is the keyword to be counted, and value is the number of times the keyword appears.

 for sentence in sentences:
       for s in sentence:
          word_count[s] += 1

The above sentence can count the number of occurrences of each word in each sentence

The following explains a few commonly used scenarios of this class:

1. If you want to count the number of occurrences of elements in a sequence

from collections import Counter
a = ['hello','world','python','newbee']
b = Counter(a)
print(b)

Insert picture description here

2. If you want to get the top few

a = [10, 8, 6, 7, 2, 8, 4, 10, 3, 7, 8, 4, 5, 7, 2, 2, 3, 8, 8, 9, 6, 2, 2, 7, 8, 7, 4, 8, 5, 2]
b = Counter(a).most_common(3)
print(b)

Insert picture description here
8 appears the most times, 7 times, 2 is 6 times, and so on. Since 3 is passed, there are other ways to count top3
, please refer to official documents.

Guess you like

Origin blog.csdn.net/weixin_45717055/article/details/112602241