Python's counter frequency statistical function

To use Python's Counter frequency statistics function, collectionsthe module should be introduced. The specific method is:

from collections import Counter

By introducing collectionsa module, you can use its Counterclasses to perform frequency statistics. For example:

lst = ['apple', 'banana', 'orange', 'apple', 'banana', 'grape', 'grape', 'grape']
cnt = Counter(lst)
print(cnt)

Output:

Counter({'grape': 3, 'apple': 2, 'banana': 2, 'orange': 1})

Among them, Counter()the function will accept an iterable object (such as a list, string, tuple, etc.) as input and return a dictionary containing the number of occurrences of each element.

Guess you like

Origin blog.csdn.net/qq_27487739/article/details/131004047