栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python:列表中出现次数最多的值

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

Python:列表中出现次数最多的值

如果要查找列表中每个元素的出现,可以使用

Counter
from的模块
collections
:-

>>> x = ['a','a','b','c','c','d']>>> from collections import Counter>>> count = Counter(x)>>> countCounter({'a': 2, 'c': 2, 'b': 1, 'd': 1})>>> count.most_common()[('a', 2), ('c', 2), ('b', 1), ('d', 1)]

因此,前两个元素在您的列表中最常见。

>>> count.most_common()[0]('a', 2)>>> count.most_common()[1]('c', 2)

或者,您还传递参数来

most_common()
指定所需的
most-common
元素数:-

>>> count.most_common(2)[('a', 2), ('c', 2)]

更新:-

您也可以先找出

max
计数,然后再找到具有该值的元素总数,然后可以将其用作参数
most_common()
:-

>>> freq_list = count.values()>>> freq_list[2, 2, 1, 1]>>> max_cnt = max(freq_list)>>> total = freq_list.count(max_cnt)>>> most_common = count.most_common(total)[('a', 2), ('c', 2)]>>> [elem[0] for elem in most_common]['a', 'c']


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

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

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