我正在写一个函数,用于计算数字列表的模式。
如果输入为[52, 99, 37, 86, 99, 99, 99, 37, 37, 37],则输出应为[37, 99]。如您所见,较小的数字应该排在第一位,但是我的代码不会这样做。有人可以修复我的代码吗?
def mode(L):
most = max(list(map(L.count, L)))
return list(set(filter(lambda x: L.count(x) == most, L)))
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是使用 collections.Counter
from collections import Counter
nums = [52, 99, 37, 86, 99, 99, 99, 37, 37, 37]
c = Counter(nums)
highest_freq = max(c.values())
mod = [n for n, freq in sorted(c.items()) if freq == highest_freq]
print(mod)
Run Code Online (Sandbox Code Playgroud)
输出:
[37, 99]
Run Code Online (Sandbox Code Playgroud)
如果只需要一项,也可以使用:
nums = [52, 99, 37, 86, 99, 99, 99, 37, 37, 37]
c = Counter(nums)
print(max(c))
Run Code Online (Sandbox Code Playgroud)
打印:
99
Run Code Online (Sandbox Code Playgroud)