在Python中是否有特纳利条件操作器?


当前回答

test: or_test ['if' or_test 'else' test] | lambdef

兴趣的一部分是:

or_test ['if' or_test 'else' test]

expression1 if expression2 else expression3

expression3 将被轻松评估(即只有在 boolean 背景下, expression2 是虚假的),并且由于重复的定义,你可以无限地链接它们(也许它可能被认为是坏风格)。

expression1 if expression2 else expression3 if expression4 else expression5 # and so on

人们学习列表的理解和发明表达可能认为这是一个难以学习的教训 - 以下不会工作,因为Python预期另一个第三个表达:

[expression1 if expression2 for element in iterable]
#                          ^-- need an else here

[expression1 for element in iterable if expression2]

expression1 if expression1 else expression2

expression1 or expression2

请注意,一些风格指南可以根据清晰度限制这种使用 - 它包装了很多意义到很少的合成。

其他回答

a if condition else b

这使得短循环,因为当状态是真实的,只有A被评估,而B根本不被评估,但当状态是虚假的,只有B被评估,而A根本不被评估。

例如:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

請注意,條件是表達,而不是表達,這意味著你無法在條件表達中使用表達,如通過,或與 = (或「增加」的表達,如 +=) 的表達:

>>> pass if False else pass
  File "<stdin>", line 1
    pass if False else pass
         ^
SyntaxError: invalid syntax

>>> # Python parses this as `x = (1 if False else y) = 2`
>>> # The `(1 if False else x)` part is actually valid, but
>>> # it can't be on the left-hand side of `=`.
>>> x = 1 if False else y = 2
  File "<stdin>", line 1
SyntaxError: cannot assign to conditional expression

>>> # If we parenthesize it instead...
>>> (x = 1) if False else (y = 2)
  File "<stdin>", line 1
    (x = 1) if False else (y = 2)
       ^
SyntaxError: invalid syntax

(在 3.8 及以上, := “walrus” 操作员允许简单地将值定义为表达式,这与此同步,但请不要这样写代码,很快就会变得非常难以理解。

# Invalid syntax: we didn't specify what the value should be if the 
# condition isn't met. It doesn't matter if we can verify that
# ahead of time.
a if True

但是,您可以使用条件表达式来分配变量如下:

x = a if True else b

例如,返回值:

# Of course we should just use the standard library `max`;
# this is just for demonstration purposes.
def my_max(a, b):
    return a if a > b else b


请记住,它是由一些Pythonists为几种原因:

你可以这样做:

[condition] and [expression_1] or [expression_2];

例子:

print(number%2 and "odd" or "even")


注: 0, 没有, 虚假, 虚假, 和 emptyString 被评为 虚假。

除0以外的任何数据都被评为真实。

如果我们“和”与0(零)的东西,结果将永远是虚假的。

0 and exp

表达式 exp 将不会被评估,因为“和”与 0 将始终被评估为零,并且不需要评估表达式。

1 or exp

exp 表达式将不会被评估,因为“或”与 1 将永远是 1. 所以不会打扰评估 exp 表达式,因为结果将是 1 无论如何(计算机优化方法)。

但是,如果

True and exp1 or exp2

同样在

False and exp1 or exp2

exp1 表达式不会被评估,因为 False 相当于 0 写作,并且与 0 做“和”将是 0 本身,但在 exp1 使用“或”之后,它将评估 exp2 表达式后“或”。


[condition] and ([expression_1] or 1) or [expression_2];

一个替代Python的条件表达

"yes" if boolean else "no"

是如下:

{True: "yes", False: "no"}[boolean]

有下列好延伸:

{True: "yes", False: "no", None: "maybe"}[boolean_or_none]

最短的替代品

("no", "yes")[boolean]

因为它是以子类(bool, int)为作用。

注意,但是:替代

yes() if boolean else no()

不是

(no(), yes())[boolean]  # bad: BOTH no() and yes() are called

(no, yes)[boolean]()

這工作很好,只要沒有,是的,應該用相同的數字呼叫。

yes("ok") if boolean else no()  # (1)

或在

yes("ok") if boolean else no("sorry")  # (2)

因此,相似的替代品既不存在(一)又几乎不可行(二)。(在罕见的情况下,根据背景,某种类似的

msg = ("sorry", "ok")[boolean]
(no, yes)[boolean](msg)

可以有意义( )

谢谢Radek Rojík的评论

如果否则版本可以写作如下:

sample_set="train" if "Train" in full_path else ("test" if "Test" in full_path else "validation")

我发现默认的Python合成val = a if cond other b cumbersome,所以有时我这样做:

iif = lambda (cond, a, b): a if cond else b
# So I can then use it like:
val = iif(cond, a, b)

当然,它有一个缺点,总是评估双方(a和b),但合成对我来说更清楚。