python中如何统计列表中元素出现的频率?
发布时间:2024-09-04 19:51:04

统计列表中元素在python中的频率:使用collections.Counter统计列表元素的数量
1、collections.Counter的作用
用于统计字符串中字符的数量,以字符为key,以数量为value。
2、调用方法
count=Counter(参数).most_common()
说明:most_common()可以添加数字,即排序后输出前几个数据,不添加数据就全部输出。
3、返回值
返回列表。
4、使用实例
fromcollectionsimportCounter
list1=[ལ1','1','2','3','1','4']
count=Counter(list1)
print(count)
#输出Counter({'1':3,'2':1,'3':1,'4':1})
print(count['1'])
#输出3
print(count.most_common(1)#出现最多次数
#[('1',3)] 