首頁 >後端開發 >Python教學 >Python找出list中最常出現元素

Python找出list中最常出現元素

高洛峰
高洛峰原創
2017-03-02 11:33:511669瀏覽

本文實例講述了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中文網!

#
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn