gpt4 book ai didi

python - 在 Python 中嵌套三元运算符

转载 作者:太空狗 更新时间:2023-10-29 18:16:49 28 4
gpt4 key购买 nike

在 Python 之禅中,Tim Peters 指出Flat 优于嵌套。。如果我理解正确,那么在 Python 中,这是:

<statement-1> if <condition> else <statement-2>

通常比这个更受欢迎:

if <condition>:
<statement-1>
else:
<statement-2>

然而,在其他语言中,我被告知不要嵌套三元运算符,而是使用传统的 if...else。那么,我的问题是我应该使用这个:

(<statement-1> if <condition-1> else <statement-2>) if <condition-2> else <statement-3>

if <condition-2>:
if <condition-1>:
<statement-1>
else:
<statement-2>
else:
<statement-3>

?特别是如果语句和条件很长,并且第一行需要拆分?

最佳答案

您的第一个 示例(可怕的单行代码)也是嵌套的。水平嵌套。您的第二个示例是垂直嵌套的。它们都是嵌套的。

那么哪个更好呢?第二个!为什么?因为“稀疏胜于密集”打破了平局。

当你是 Tim Peters 时很容易 - 哈哈 ;-)

关于python - 在 Python 中嵌套三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19646056/

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