Python逻辑检查的执行顺序

标签 python python-3.x

所以我的老板在快速搜索并替换代码并打开拉取请求后(偶然)想到了这个,其中标签始终是一个字符串:

if "team_" in tag in tag:

令我惊讶的是,这确实有效!不太确定为什么。我本来期望从左到右解析它并得到一个错误,像这样

>>> ("team_" in "something") in "something"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not bool

或者甚至在最坏的情况下,从右到左解析它(我觉得这很奇怪,但我们假设它是这样工作的)

>>> "team_" in ("something" in "something")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable

但我得到的是

>>> "team_" in "something" in "something"
False
>>> 
>>> "some" in "something" in "something"
True
>>> 

有人可以向我解释一下它是如何/为什么起作用的吗?

最佳答案

其工作原理与

相同
1 < x < 10

有效。 Python 允许比较运算符被链接起来,所以这相当于

1 < x and x < 10

同样的逻辑

"team_" in tag in tag

相当于

"team_" in tag and tag in tag

tag 是字符串时,这实际上相当于 tag 中的 "team_",因为字符串始终在其自身中。但是,如果 tag 是列表或其他容器,则通常为 false,因为容器通常不包含其自身的实例(可以进行递归引用,例如 mylist.append(mylist ),然后 mylist in mylist 将为 true)。

关于Python逻辑检查的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75189130/

相关文章:

python - Python 3 中的连接列表

Python:读取具有不同分隔符(空格)的文本文件的有效方法

python - 快速有效地减去数组的方法

python - PIL属性错误: Shape when creating an array

python - 使用 pandas apply 和用户定义的函数返回多列

python - 切换到Python 3.6.5_1后,显示的版本仍然是3.7.2

python - 如何在 Python 3.5 中使用 async/await?

python - python3的pycharm编码错误

python - 如何使用 Python 连接多个 netCDF 文件中的数据

python - 从可迭代对象中填充计数字典