查找列表中出现次数最多的项目 [英] Find the item with maximum occurrences in a list
本文介绍了查找列表中出现次数最多的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 中,我有一个列表:
In Python, I have a list:
L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
我想确定出现次数最多的项目.我能够解决它,但我需要最快的方法.我知道对此有一个很好的 Pythonic 答案.
I want to identify the item that occurred the highest number of times. I am able to solve it but I need the fastest way to do so. I know there is a nice Pythonic answer to this.
推荐答案
这是一个 defaultdict
解决方案,适用于 Python 2.5 及更高版本:
Here is a defaultdict
solution that will work with Python versions 2.5 and above:
from collections import defaultdict
L = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
d = defaultdict(int)
for i in L:
d[i] += 1
result = max(d.iteritems(), key=lambda x: x[1])
print result
# (4, 6)
# The number 4 occurs 6 times
注意如果 L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 7, 7, 7, 7, 7, 56, 6, 7, 67]
然后有六个 4 和六个 7.但是,结果将是 (4, 6)
,即六个 4.
Note if L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 7, 7, 7, 7, 7, 56, 6, 7, 67]
then there are six 4s and six 7s. However, the result will be (4, 6)
i.e. six 4s.
这篇关于查找列表中出现次数最多的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文