
上QQ阅读APP看书,第一时间看更新
2.1.3 找出列表中出现次数最多的元素
在Python程序中,如果想找出列表中出现次数最多的元素,可以考虑使用collections模块中的Counter类,调用Counter类中的函数most_common()来实现上述功能。下面的实例文件most.py演示了使用函数most_common()找出列表中出现次数最多的元素的过程。
源码路径:daima\第2章\most.py
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' ] from collections import Counter word_counts = Counter(words) top_three = word_counts.most_common(3) print(top_three)
在上述代码中预先定义了一个列表words,在里面保存了一系列的英文单词,使用函数most_common()找出哪些单词出现的次数最多。执行结果如图2-6所示。

图2-6 执行结果