为什么在Python中执行"0,0 ==(0,0)"?等于“((0,False))"? [英] Why in Python does "0, 0 == (0, 0)" equal "(0, False)"?
问题描述
在Python中(我仅使用Python 3.6进行过检查,但我相信它也适用于许多以前的版本):
In Python (I checked only with Python 3.6 but I believe it should hold for many of the previous versions as well):
(0, 0) == 0, 0 # results in a two element tuple: (False, 0)
0, 0 == (0, 0) # results in a two element tuple: (0, False)
(0, 0) == (0, 0) # results in a boolean True
但是:
a = 0, 0
b = (0, 0)
a == b # results in a boolean True
为什么两种方法的结果不同?相等运算符是否以不同的方式处理元组?
Why does the result differ between the two approaches? Does the equality operator handle tuples differently?
推荐答案
前两个表达式都解析为元组:
The first two expressions both parse as tuples:
-
(0, 0) == 0
(即False
),后跟0
-
0
,然后是0 == (0, 0)
(仍然是False
).
(0, 0) == 0
(which isFalse
), followed by0
0
, followed by0 == (0, 0)
(which is stillFalse
that way around).
之所以这样对表达式进行拆分,是因为逗号分隔符相对于相等运算符具有相对的优先级:Python看到一个包含两个表达式的元组,其中一个恰好是一个相等测试,而不是两个元组之间的相等测试
The expressions are split that way because of the relative precedence of the comma separator compared to the equality operator: Python sees a tuple containing two expressions, one of which happens to be an equality test, instead of an equality test between two tuples.
但是在第二组语句中,a = 0, 0
不能是一个元组.元组是值的集合,与相等性测试不同的是,赋值在Python中没有值.赋值不是表达式,而是语句.它没有可以包含在元组或任何其他周围表达式中的值.如果您尝试使用(a = 0), 0
之类的方法来强制将其解释为元组,则会出现语法错误.这样,将元组分配给变量(可以通过将其编写为a = (0, 0)
来使其更明确)作为唯一的有效解释a = 0, 0
.
But in your second set of statements, a = 0, 0
cannot be a tuple. A tuple is a collection of values, and unlike an equality test, assignment has no value in Python. An assignment is not an expression, but a statement; it does not have a value that can be included into a tuple or any other surrounding expression. If you tried something like (a = 0), 0
in order to force interpretation as a tuple, you would get a syntax error. That leaves the assignment of a tuple to a variable – which could be made more explicit by writing it a = (0, 0)
– as the only valid interpretation of a = 0, 0
.
因此,即使在a
的赋值上没有括号,它和b
都将被赋值为(0,0)
,因此a == b
也是True
.
So even without the parentheses on the assignment to a
, both it and b
get assigned the value (0,0)
, so a == b
is therefore True
.
这篇关于为什么在Python中执行"0,0 ==(0,0)"?等于“((0,False))"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!