Python找出list中最常出现元素的方法

yipeiwu_com6年前Python基础

本文实例讲述了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)操作技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python提取页面内url列表的方法

本文实例讲述了python提取页面内url列表的方法。分享给大家供大家参考。具体实现方法如下: from bs4 import BeautifulSoup import time,r...

python 文件与目录操作

1)os.path 1.1 os.path.isabs(path) 是否是绝对路径 1.2 os.path.isfile(path) 1.3 os.path.isdir(path) 1....

对python dataframe逻辑取值的方法详解

我遇到的一个小需求,就是希望通过判断pandas dataframe中一列的值在两个条件范围(比如下面代码中所描述的逻辑,取小于u-3ε和大于u+3ε的值),然后取出dataframe中...

Python实现读取json文件到excel表

本文实例为大家分享了Python实现读取json文件到excel表,供大家参考,具体内容如下 一、需求 1、'score.json' 文件内容: { "1":["小花",99,1...

搞笑的程序猿:看看你是哪种Python程序员

不久前,在互联网上出现了一篇有趣的文章,讲的是对于同一个问题,不同层次的Python程序员编出的Python代码,显示出了不同的风格,代码都很简单,有趣。下面让我们一起来看看一个Pyth...