gpt4 book ai didi

python - 在 Python 中使用缩短的 if else 语句返回

转载 作者:行者123 更新时间:2023-11-28 20:38:48 25 4
gpt4 key购买 nike

我正在研究缩短普通 if else 语句的方法。我发现的一种格式是更改此格式:

if x == 1:
print("Yes")
else:
print("No")

进入这个:

print("Yes") if x == 1 else print("No")

上面的代码被认为是 pythonic 的吗?否则,缩短 if else 语句的 pythonic 方法是什么?

我还尝试使用 return 而不是 print。我试过了

return total if x == 1 else return half

这导致第二个返回的语句无法访问。有没有我看不到的方法?

最后,我尝试在代码中使用 else if 而不是 else ,但这也行不通。

print(total) if x == 1 else print(half) if x == 2

上面的代码在逻辑上可能看起来很愚蠢。我是否错过了正确的格式,或者真的不可能用这种格式执行 returnelse if 吗?

最佳答案

表格

print("Yes") if x == 1 else print("No")

通常不被认为是 Pythonic,因为 ... if ... else ... 是一个表达式,您将丢弃该表达式产生的值(总是 None)。您可以使用 print("Yes"if x == 1 else "No"),这是 Pythonic,因为条件表达式的值用作 print 的参数。

表格

return total if x == 1 else return half

无法工作,因为 return 是一个语句并且必须出现在逻辑行的开头。相反,使用

return total if x == 1 else half

(与 return (total if x == 1 else half) 解析相同)

代码

 print(total) if x == 1 else print(half) if x == 2

也不起作用 - 条件表达式是 ... if ... else ...,即每个 if 必须与后面的 else 配对它;您的第二个 if 缺少 else 子句;你可以使用

 print(total) if x == 1 else print(half) if x == 2 else print('something else')

同样,这不会被认为是非常 pythonic 的;但你可以使用

 print(total if x == 1 else half if x == 2 else 'something else')

也不是说它会好得多。


最后,如果您正在参加代码高尔夫

print("Yes" if x == 1 else "No")

可以缩短为

print(('No', 'Yes')[x == 1])

通过使用 True == 1False == 0 并使用它们来索引元组。

关于python - 在 Python 中使用缩短的 if else 语句返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40317284/

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