简体   繁体   English

在Python中嵌套三元运算符

[英]Nesting the ternary operator in Python

In the Zen of Python, Tim Peters states that Flat is better than nested. 在Python的禅宗中,蒂姆·彼得斯指出Flat is better than nested. . If I have understood that correctly, then in Python, this: 如果我已正确理解,那么在Python中,这个:

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

is generally preferred over this: 通常比这更受欢迎:

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

However, in other languages, I have been told not to nest the ternary operator, and the instead use the traditional if...else . 但是,在其他语言中,我被告知不要嵌套三元运算符,而是使用传统的if...else My question, then, is should I use this: 那么,我的问题是我应该使用这个:

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

or 要么

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

? Particularly if the statements and conditions are long, and the first line would need splitting? 特别是如果陈述和条件很长,第一行需要拆分?

Your first example (the horrid one-liner) is nested too. 你的第一个例子(可怕的单行)也是嵌套的。 Horizontally nested. 水平嵌套。 Your second example is vertically nested. 你的第二个例子是垂直嵌套的。 They're both nested. 它们都是嵌套的。

So which is better? 哪个更好? The second one! 第二个! Why? 为什么? Because "sparse is better than dense" breaks the tie. 因为“稀疏优于密集”打破了平局。

It's easy when you're Tim Peters - LOL ;-) 当你是蒂姆·彼得斯 - LOL时很容易;-)

"Flat is better than nested" is about module organization and perhaps data structures, not your source code. “Flat比嵌套好”是关于模块组织和数据结构,而不是源代码。 The standard library, for example, mostly exists as top-level modules with very little nesting. 例如,标准库主要作为顶级模块存在,嵌套非常少。

Don't nest the ternary operator, or even use it at all if you can avoid it. 如果可以避免,请不要嵌套三元运算符,甚至根本不使用它。 Complex is better than complicated. 复杂比复杂更好。 :) :)

To my understanding, this is "flater": 根据我的理解,这是“更大的”:

if <condition_2> and <condition_1>:
  <statement_1>
elif <condition_2>:
  <statement_2>
else:
  <statement_3>

The order of the conditions to check is important, eg should you put <condition_2> only as the first order of checking, then <statement_1> will never be called. 要检查的条件的顺序很重要,例如,如果只将<condition_2>作为第一个检查顺序,那么<statement_1>将永远不会被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM