在 Java 或 C 中我们有 <condition> ? X : Y
, 转换为 Python 为 X if <condition> else Y
.
但是还有这个小技巧:<condition> and X or Y
.
虽然我理解它等同于上述三元运算符,但我发现很难理解 and
是如何实现的和 or
运算符(operator)能够产生正确的结果。这背后的逻辑是什么?
最佳答案
While I understand that it's equivalent to the aforementioned ternary operators
这是不正确的:
In [32]: True and 0 or 1
Out[32]: 1
In [33]: True and 2 or 1
Out[33]: 2
为什么第一个表达式返回 1
(即 Y
),而条件为 True
而“预期”答案为 0
(即 X
)?
根据文档:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
因此,True and 0 or 1
计算and
运算符的第一个参数,即True
。然后它返回第二个参数,即 0
。
由于 True 和 0
返回假值,or
运算符返回第二个参数(即 1
)
关于python - X 和 Y 或 Z - 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39080416/