python - 为什么在 Python 中是 ‘==‘ coming before ‘in’?

标签 python

<分区>

以下代码输出 False,根据 Python 操作顺序它应该输出 True(顺序应该是 -> ==,而不是相反)。为什么 == coming before in?

y = "33"
"3" in y == True

输出

False

最佳答案

现有答案提供了有用的建议,您不应将 bool 值与 True 进行比较因为它是多余的。但是,没有一个答案真正回答了根本问题:“为什么 "3" in y == True 的计算结果为 False?”。

juanpa.arrivillaga 在评论中回答了这个问题:

Also, this is an instance of operator chaining, since == and in both count as comparison operators. So this is evaluated as ('3' in y) and (y == True)

在 Python 中,比较运算符可以链接。例如,如果你想检查 a , b , c , 和 d正在增加,你可以写a < b < c < d而不是 a < b and b < c and c < d .同样,您可以使用 a == b == c == d 检查它们是否都相等.

链式比较在 Python 文档中描述 here :

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

关于python - 为什么在 Python 中是 ‘==‘ coming before ‘in’?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53412942/

相关文章:

python - Django REST 框架 : method PUT not allowed in ViewSet with def update()

python - 分割数据集以解决分类问题的正确程序是什么?

python - 如何向现有对象方法添加装饰器?

Python自动截图,无抓屏。仅限 Linux/Unix/OS X

python - 您可以更改 Django Admin 应用程序中的字段标签吗?

python - 在 python 中使用 % 运算符的 %s 可变长度

python - 正确捕获 boto3 错误

python - 将日期时间列转换为不同的时区 Pandas

Python 导入模块为 None

python - 使用 python 订阅 ROS sensor_msg/Image