使用collections模块对Python中数组中所有元素的频率进行计数

由于python允许列表中有重复元素,因此我们可以让一个元素出现多次。列表中元素的频率指示元素在列表中出现的次数。在本文中,我们使用collections模块的Counter函数来查找列表中每个项目的频率。

语法

Syntax: Counter(list)
Where list is an iterable in python

示例

下面的代码使用Counter()来跟踪频率并items()在计数器功能的结果中迭代每个项目,以便以格式化的方式进行打印。

from collections import Counter
list = ['Mon', 'Tue', 'Wed', 'Mon','Mon','Tue']

# Finding count of each element
list_freq= (Counter(list))

#Printing result of counter
print(list_freq)

# Printing it using loop
for key, value in list_freq.items():
   print(key, " has count ", value)

输出结果

运行上面的代码给我们以下结果-

Counter({'Mon': 3, 'Tue': 2, 'Wed': 1})
Mon has count 3
Tue has count 2
Wed has count 1