使用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热门推荐
10 宝宝简短的生日祝福语
11 发给导师的祝福语简短
12 生日祝福语简短独特格式
13 祝福语年轻回复文案简短
14 宝宝生病简短祝福语大全
15 2026猪年祝福语简短语
16 送离职同事简短祝福语
17 公司个人新年祝福语简短
18 简短新婚铺被子祝福语