您可以使用defaultdict 来实现:
from collections import defaultdict
def highest_repeated_value(nums):
cache = defaultdict(int)
for i in nums:
cache[i] += 1
return max(cache.items(), key=lambda x: x[1])
nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
print(highest_repeated_value(nums))
请注意,如果nums = [4, 4, 4, 4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2] 则有five 4s 和five 2s。但是,结果将是(4, 5),即five 4s。
如果您使用numpy 并且列表包含所有非负ints,则可以使用numpy.bincounts:
import numpy
def highest_repeated_value(nums):
counts = numpy.bincount(nums)
num = numpy.argmax(counts)
val = numpy.max(counts)
return num, val
nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
print(highest_repeated_value(nums))
如果你只是想在 python 中工作而不使用numpy,collections.Counter 是一个很好的处理方式。
from collections import Counter
def highest_repeated_value(nums):
return Counter(nums).most_common()[0]
nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
print(highest_repeated_value(nums))