找出列表中出現次數最多的元素
- 在Python程序中,如果想找出列表中出現次數最多的元素,可以考慮使用collections模塊中的Counter類,調用Counter類中的函數most_common() 來實現上述功能。
from collections import Counter
words = [
'look', 'into', 'my', 'AAA', 'look', 'into', 'my', 'AAA',
'the', 'AAA', 'the', 'AAA', 'the', 'eyes', 'not', 'BBB', 'the',
'AAA', "don't", 'BBB', 'around', 'the', 'AAA', 'look', 'into',
'BBB', 'AAA', "BBB", 'under'
]
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)