简体   繁体   English

Python三元运算符行为

[英]python ternary operator behaviour

when I evaluate the following operation 当我评估以下操作时

0 if True else 1 + 1 if False else 1

it evaluates to 0 however when I write with brackets like 它的值为0,但是当我用方括号写时

( 0 if True else 1 ) + ( 0 if False else 1 )

it evaluates correctly to 1 , what is happening in the first case. 它正确地计算为1,这是第一种情况。

0 if True else 1 + 1 if False else 1

is actually: 实际上是:

(0) if (True) else ((1 + 1) if (False) else (1))

which is definitely differs from what you want: 这绝对不同于您想要的:

((0) if (True) else (1)) + ((1) if (False) else (1))

as ternary operator is read from left to right and + has lower precedence than conditional operators. 因为ternary operator left to right读取,并且+优先级低于条件运算符。 So, these two are equivalent: 因此,这两个是等效的:

>>> 0 if True else 1 + 1 if False else 1
0
>>> 0 if True else ( (1 + 1) if False else 1)
0

三元运算符看起来像“条件?如果为true的值:如果为false的值”,但是python似乎不支持它,但是我们可以使用if-else进行替换。stype类似于“条件if(b_1)else b_2 ,因此可以依赖它进行匹配。如果b_1为True,则为condition;如果b_2为True,则为b_2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM