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

时间:2021-12-11 14:04:56

本文实例讲述了Python找出list中最常出现元素的方法。分享给大家供大家参考,具体如下:

假设一个list中保存着各种元素,需要统计每个元素出现的个数,并打印出最常出现的前三个元素分别是什么。list如下:

复制代码 代码如下:
word_list =["is","you","are","I","am","OK","is","OK","She","is","OK","is","I"]

 

方法一(常规方法):

?
1
2
3
4
5
6
7
8
9
10
11
>>> 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

?
1
2
3
>>> from collections import Counter
>>> c = Counter(word_list)
>>> c.most_common(3)

方法三:

?
1
2
3
4
>>> 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程序设计有所帮助。