可以通过两种方式来实现。一种是使用Python中的字典来记录每个数字的频率,然后按照出现的顺序排序并返回最大频率。另一种是使用Python中的Counter函数来简化操作。
方法一:
def frequency(numbers):
counts = {}
max_count = 0
for n in numbers:
if n not in counts:
counts[n] = 1
else:
counts[n] += 1
if counts[n] > max_count:
max_count = counts[n]
return max_count
numbers = [1, 2, 3, 2, 1, 2, 3, 4, 2, 2]
print(frequency(numbers))
输出:
5
方法二:
from collections import Counter
def frequency(numbers):
counts = Counter(numbers)
max_count = 0
for n in numbers:
if counts[n] > max_count:
max_count = counts[n]
return max_count
numbers = [1, 2, 3, 2, 1, 2, 3, 4, 2, 2]
print(frequency(numbers))
输出:
5
上述代码示例中,我们首先定义一个函数frequency
,该函数接受一个列表numbers
作为输入,然后使用Counter
函数或字典来记录每个数字出现的频率。最后遍历numbers
列表并比较每个数字的频率,然后返回最大频率。