Python:表达式中相等性/不等式的真实执行顺序?

huangapple go评论64阅读模式
英文:

Python: real order of execution for equalities/inequalities in expressions?

问题

请看下面这段“狡猾”的Python代码:

>>> 1 == 2 < 3
False

根据Python文档,所有运算符in, not in, is, is not, <, <=, >, >=, !=, ==的优先级相同,但这里发生的情况似乎矛盾。

在实验后,我得到了更奇怪的结果:

>>> (1 == 2) < 3
True
>>> 1 == (2 < 3)
True

发生了什么?

(注意)

>>> True == 1
True
>>> True == 2
False
>>> False == 0
True
>>> False == -1
False

布尔类型是int的子类,True代表1,False代表0。

这可能是一个实现细节,不同版本可能会有所不同,所以我主要关心的是Python 3.10版本。

英文:

Imagine this "sneaky" python code:

&gt;&gt;&gt; 1 == 2 &lt; 3
False

According to Python documentation all of the operators in, not in, is, is not, &lt;, &lt;=, &gt;, &gt;=, !=, == have the same priority, but what happens here seems contradictory.

I get even weirder results after experimenting:

&gt;&gt;&gt; (1 == 2) &lt; 3
True
&gt;&gt;&gt; 1 == (2 &lt; 3)
True

What is going on?

(Note)

&gt;&gt;&gt; True == 1
True
&gt;&gt;&gt; True == 2
False
&gt;&gt;&gt; False == 0
True
&gt;&gt;&gt; False == -1
False

Boolean type is a subclass of int and True represents 1 and False represents 0.

This is likely an implementation detail and may differ from version to version, so I'm mostly interested in python 3.10.

答案1

得分: 1

Python允许您链接条件,它使用and来组合它们。所以

1 == 2 and 2 < 3

等同于

1 == 2 and 2 < 3

这在不等式链中非常有用,例如 1 < x < 10 将在 x110 之间时为真。

当您添加括号时,它不再是一个链。所以

(1 == 2) < 3

等同于

False < 3

TrueFalse 等同于 01,因此 False < 30 < 3 是相同的,也就是 True

类似地,

1 == (2 < 3)

等同于

1 == True

这等同于

1 == 1

显然是 True

英文:

Python allows you to chain conditions, it combines them with and. So

1 == 2 &lt; 3

is equivalent to

1 == 2 and 2 &lt; 3

This is most useful for chains of inequalities, e.g. 1 &lt; x &lt; 10 will be true if x is between 1 and 10.

WHen you add parentheses, it's not a chain any more. So

(1 == 2) &lt; 3

is equivalent to

False &lt; 3

True and False are equivalent to 0 and 1, so False &lt; 3 is the same as 0 &lt; 3, which is True.

Similarly,

1 == (2 &lt; 3)

is equivalent to

1 == True

which is equivalent to

1 == 1

which is obviously True.

huangapple
  • 本文由 发表于 2023年6月8日 01:11:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定