为什么在Python中执行"0,0 ==(0,0)"?等于“((0,False))"? [英] Why in Python does "0, 0 == (0, 0)" equal "(0, False)"?

查看:155
本文介绍了为什么在Python中执行"0,0 ==(0,0)"?等于“((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:

  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.

这篇关于为什么在Python中执行"0,0 ==(0,0)"?等于“((0,False))"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆