且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在列表中查找出现次数最多的项目

更新时间:2023-11-28 15:58:16

这是一个 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] 然后有六个4s和六个7s.但是,结果将是(4,6),即六个4s.

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.