python - X 和 Y 或 Z - 三元运算符

标签 python syntax ternary-operator

在 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/

相关文章:

c - C 中的三元(条件)运算符

python - pyparsing 检索动态长度字符串的结果键

python - 尝试向下滚动带有水平 ScrollView 的垂直 ScrollView 时,Kivy 出现问题

javascript - MDN javascript语法文档中每个参数之间的括号是什么意思?

JSON JQ 如果没有 else

css - 如何做一个内联比较条件来应用徽章中的一个类?

python - 在 Apache Spark 中指定输出文件名

python - 没有名为 'prompt_toolkit.formatted_text' 的模块

mysql - 尝试/捕获语法

javascript - 如何使用一个默认条件对 3 个条件执行三元语句