Python三元运算符行为 [英] python ternary operator behaviour

查看:81
本文介绍了Python三元运算符行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我评估以下操作时

 如果为True,则为0,否则为1;如果为False,则为1,否则为1 

它的值为0,但是当我使用方括号



<$ p $书写时p> (如果为True则为0则为0)+(如果为False则为1则为0)

它正确地计算为1,这是第一种情况。

解决方案

 如果为True,则为0;否则为1;如果为False,则为1; 

实际上是:

 (0)如果(真)否则((1 + 1)如果(假)否则(1))

这与您想要的绝对不同:

 (((0)如果(真)否则(1))+((1)如果(假)否则(1))


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 if True else 1 ) + ( 0 if False else 1 )

it evaluates correctly to 1 , what is happening in the first case.

解决方案

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))

这篇关于Python三元运算符行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆