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


当前回答

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

其他回答

<表达 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

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

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

一个替代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的评论

模拟 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'

在Python中,Ternary Operator的合成是:

假如他是真實的,

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

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

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