gpt4 book ai didi

python - 列表的查找方式

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:01 24 4
gpt4 key购买 nike

我正在编写一个函数来计算数字列表的一个或多个众数。

如果输入是[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

关于python - 列表的查找方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57133679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com