我正在编写一个函数来计算数字列表的一个或多个众数。
如果输入是[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)))
请您参考如下方法:
另一种解决方案是使用 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)
输出:
[37, 99]
如果你只需要一个项目,你也可以只使用:
nums = [52, 99, 37, 86, 99, 99, 99, 37, 37, 37]
c = Counter(nums)
print(max(c))
打印:
99
