为什么在 Python 中执行“0, 0 == (0, 0)"?等于“(0,假)"?

2022-01-19 00:00:00 python tuples operator-precedence

问题描述

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

  1. (0, 0) == 0(即False),后跟0
  2. 0,然后是 0 == (0, 0)(这样仍然是 False).
  1. (0, 0) == 0 (which is False), followed by 0
  2. 0, followed by 0 == (0, 0) (which is still False 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.

相关文章