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


当前回答

模拟 Python Ternary 操作器。

例如

a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()

出口:

'b greater than a'

其他回答

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

[expression] and [on_true] or [on_false]

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

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

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

模拟 Python Ternary 操作器。

例如

a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()

出口:

'b greater than a'

是的,它有,但它与C类似的编程语言不同(这是条件? value_if_true : value_if_false

在 Python 中,它如下: value_if_true 如果另一个条件值_if_false

例如: even_or_odd = “even” 如果 x % 2 == 0 其他 “odd”

在Python中,Ternary Operator的合成是:

假如他是真實的,

使用这个合成,这里是我们如何使用Python的Ternary操作器重写上面的代码:

game_type = 'home'
shirt = 'white' if game_type == 'home' else 'green'

请注意,表达式可能是任何类型的表达式,包括函数呼叫,返回值,评估为真实或虚假。

其他答案是正确的谈论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)