带嵌套三元运算符的字符串连接忽略该字符串

Pra*_*nna 0 python python-3.x

我发现以下两个陈述之间存在差异.

message = "a is " + "greater than" if a > 10 else "less than" if a <10 else "equal to" + " 10"
Run Code Online (Sandbox Code Playgroud)

message = "a is " + ("greater than" if a > 10 else ("less than" if a <10 else "equal to")) + " 10"
Run Code Online (Sandbox Code Playgroud)

有人可以解释这里发生了什么

khe*_*ood 5

第一个被解释为:

("a is "+"greater than") if a > 10 else "less than" if a < 10 else ("equal to"+" 10")
Run Code Online (Sandbox Code Playgroud)

请参阅文档:"条件表达式具有所有Python操作的最低优先级."

这就是为什么你可以选择用括号分组表达式的部分内容.