栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python函数.most

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python函数.most

函数most.common()是python内建模块collections中的counter类的函数,用来计算列表中元素出现的频数,返回的结果是元组列表,不是字典.

from collections import Counter
# 统计字符串
list0 = ['a', 'b', 'b', 'a', 'a', 'd', 'a', 'c', 'c', 'b', 'd']
print(Counter(list0).most_common())

输出结果为:

如果想要筛选出出现频率最大的前n个,则需给most.common()一个参数n,如下:

from collections import Counter

list0 = ['a', 'b', 'b', 'a', 'a', 'e', 'd', 'a', 'c', 'e', 'c', 'b', 'd', 'e', 'd', 'a']
list1 = Counter(list0)
print(list1)
print(list1.most_common(3))

输出结果是:

list1输出的原则是按照在list0中出现的先后、频数的大小排列的, 然后利用函数list1.most_common(3)将list1中前3个元组组成的列表打印出来,即是前3个出现频率最大的三个.

如果我们需要出现频率最大的一个,只需要将Counter()处理之后的第一个元素筛选出来即可(第一个一定是最大的,但不一定是唯一最大的),如下:

from collections import Counter

list0 = ['a', 'b', 'b', 'a', 'a', 'e', 'd', 'a', 'c', 'e', 'c', 'b', 'd', 'e', 'd', 'a']
list1 = Counter(list0)
print(list1)
print(list1.most_common()[0])

输出为:

 可知出现频率最大的元素:a,出现的次数:5

如果想要筛选出出现频率最大的元素(在这里就是将“a”筛选出来),则只需要在上述代码的最后一行代码后面再加一个[0]就ok了.

print(list1.most_common()[0][0])

上面的输出结果就会变为:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/766860.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号