找出列表中出现次数最多的元素
- 在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)