gpt4 book ai didi

python - 在 Python 中,只返回列表中最大奇数的方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:45 25 4
gpt4 key购买 nike

如果您有一个数字列表,如何使用max() 函数只返回最大奇数?

我假设它与 int % 2 != 0 有关,但我不确定还有什么。


我还必须在不使用 max() 的情况下返回总的最大整数,但我通过对列表进行排序并使用 list[-1] 解决了这个问题。

最佳答案

max(i for i in my_list if i % 2)

编辑:没有max():

def highest_odd(seq):
"""
Return the highest odd number in `seq`.
If there are no odd numbers, then return `None`.

"""
for i in sorted(seq, reverse=True):
if i % 2:
return i

关于python - 在 Python 中,只返回列表中最大奇数的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9185443/

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