python找出list中最常出现元素

本文实例讲述了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找出list中最常出现元素相关文章请关注php中文网!

Posted in 未分类

发表评论