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