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


当前回答

a if condition else b

记住这个金字塔,如果你有记住问题:

     condition
  if           else
a                   b 

其他回答

是的,Python有一个特纳运营商,这里是合成和一个示例代码来展示相同的:)

#[On true] if [expression] else[On false]
# if the expression evaluates to true then it will pass On true otherwise On false

a = input("Enter the First Number ")
b = input("Enter the Second Number ")

print("A is Bigger") if a>b else print("B is Bigger")

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

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

在 2.5 之前的版本中,有以下技巧:

[expression] and [on_true] or [on_false]

它可以提供错误的结果,当 on_true 具有虚假的 Boolean 值。

雖然它有評估表達的好處留在右邊,這在我看來更清楚。

是否有“C”的“?”:“特纳利运营商的同等值?

你可以这样做:

[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操作员. 我想补充提到一个场景,操作员经常使用,但有一个更好的字符。

假设我们希望使用选项_值与默认值,如果它没有设置:

run_algorithm(option_value if option_value is not None else 10)

或者,如果选项_值从未设置为虚假值(0,“”,等),

run_algorithm(option_value if option_value else 10)

但是,在这种情况下,一个越来越好的解决方案只是写作。

run_algorithm(option_value or 10)