首页 > 解决方案 > 谁能解释为什么 True, True == (True, True) 的输出是 (True, False)?

问题描述

我尝试像下面的代码一样与 Python 进行比较,但对产生的输出感到困惑。

谁能解释为什么输出是这样的?

>>> True, True == True, True
(True, True, True)
>>> True, True == (True, True)
(True, False)

标签: pythonpython-3.x

解决方案


因为运算符优先级。==的优先级高于,,因此第一个表达式被视为您已编写

True, (True == True), True

您的第二个表达式被视为

True, (True == (True, True))

如果要比较==element-wise 的两侧,则需要在两侧加上括号:

(True, True) == (True, True)

这将返回True

请注意,逗号并不是严格意义上的 operator,因此为了理解这种行为,它已经足够接近了。


推荐阅读