本文實例講述了Python找出list中最常出現元素的方法。分享給大家供大家參考,具體如下:
假設一個list中保存著各種元素,需要統計每個元素出現的個數,并打印出最常出現的前三個元素分別是什么。list如下:
方法一(常規方法):
>>> 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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選