在Python中是否有特纳利条件操作器?
当前回答
a if condition else b
记住这个金字塔,如果你有记住问题:
condition
if else
a b
其他回答
有多种方式,最简单的是在“印刷”方法中使用状态。
你可以使用
print("Twenty" if number == 20 else "Not twenty")
相当于:
if number == 20:
print("Twenty")
else:
print("Not twenty")
因此,可以打印超过两份声明,例如:
if number == 20:
print("Twenty")
elif number < 20:
print("Lesser")
elif 30 > number > 20:
print("Between")
else:
print("Greater")
可以写作如:
print("Twenty" if number == 20 else "Lesser" if number < 20 else "Between" if 30 > number > 20 else "Greater")
<表达 1> 如果 <条件> 其他 <表达 2>
a = 1
b = 2
1 if a > b else -1
# Output is -1
1 if a > b else -1 if a < b else 0
# Output is -1
对于 Python 2.5 或更高版本,有一个具体的合成:
[on_true] if [cond] else [on_false]
在更老的Pythons中,一个特纳运营商没有实施,但可以模拟它。
cond and on_true or on_false
雖然有一個可能的問題,即如果 cond 評估到 True 和 on_true 評估到 False 然後 on_false 返回而不是 on_true. 如果你想要這種行為的方法是 OK,否則使用此方法:
{True: on_true, False: on_false}[cond is True] # is True, not == True
可以包装的:
def q(cond, on_true, on_false)
return {True: on_true, False: on_false}[cond is True]
以此方式使用:
q(cond, on_true, on_false)
它与所有 Python 版本兼容。
a if condition else b
记住这个金字塔,如果你有记住问题:
condition
if else
a b
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为几种原因: