Python找出list中最常出现元素的方法
作者:zeo 时间:2022-10-31 14:24:38
本文实例讲述了Python找出list中最常出现元素的方法。分享给大家供大家参考,具体如下:
假设一个list中保存着各种元素,需要统计每个元素出现的个数,并打印出最常出现的前三个元素分别是什么。list如下:
word_list =["is","you","are","I","am","OK","is","OK","She","is","OK","is","I"]
方法一(常规方法):
>>> word_counter ={}
>>> for word in word_list:
if word in word_counter:
word_counter[word] +=1
else:
word_counter[word] = 1
>>> popular_word =sorted(word_counter, key = word_counter.get, reverse = True)
)
>>> top_3 = popular_word[:3]
>>> top_3
['is', 'OK', 'I']
方法二:适用于Python2.7
>>> from collections import Counter
>>> c = Counter(word_list)
>>> c.most_common(3)
方法三:
>>> counter ={}
>>> for i in word_list: counter[i] = counter.get(i, 0) + 1
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(4, 'is'), (3, 'OK'), (2, 'I')]
希望本文所述对大家Python程序设计有所帮助。
标签:Python,list
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
web标准页面知识必备 Ⅰ
2008-03-06 13:24:00
javascript实现鼠标选取拖动或Ctrl选取拖动
2021-08-21 19:08:33
15行Python代码带你轻松理解令牌桶算法
2021-05-05 01:18:05
![](https://img.aspxhome.com/file/2023/1/71561_0s.jpg)
jQuery 选择器的使用
2008-01-21 13:07:00
Python采集二手车数据的超详细讲解
2022-09-23 00:58:22
![](https://img.aspxhome.com/file/2023/8/75078_0s.png)
Python程序暂停的正常处理方法
2023-07-17 23:21:47
python编写学生成绩管理系统的逻辑结构及功能实现
2021-08-23 18:32:21
![](https://img.aspxhome.com/file/2023/6/99106_0s.png)
python 多线程threading程序详情
2021-03-23 10:07:34
TensorFlow损失函数专题详解
2023-08-17 10:12:13
![](https://img.aspxhome.com/file/2023/3/85303_0s.gif)
Python入门教程 超详细1小时学会Python
2023-06-13 23:34:12
![](https://img.aspxhome.com/file/2023/1/59131_0s.gif)
python机器学习基础K近邻算法详解KNN
2024-01-01 05:44:57
![](https://img.aspxhome.com/file/2023/9/78739_0s.png)
如何实现对整个站点所有页面的操作?
2010-05-19 21:20:00
jQuery 1.3.3 新功能[译]
2009-06-04 12:23:00
Python判断变量名是否合法的方法示例
2022-07-31 19:05:12
![](https://img.aspxhome.com/file/2023/1/68411_0s.png)
div + ajax + 分页函数
2009-10-18 11:28:00
在Sublime Editor中配置Python环境的详细教程
2023-08-14 08:33:26
![](https://img.aspxhome.com/file/2023/8/97648_0s.png)
利用Python如何生成hash值示例详解
2022-02-28 23:29:25
解析Tensorflow之MNIST的使用
2021-09-06 03:34:27
![](https://img.aspxhome.com/file/2023/9/76719_0s.jpg)
XML轻松学习手册(3)XML的术语
2008-09-05 17:17:00
Python报错SyntaxError:unexpected EOF while parsing的解决办法
2023-10-01 10:29:54