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