in运算符链接产生意外结果 [英] Unexpected result with `in` operator chaining
问题描述
据我所知,Python中的in
运算符无法链接,或者至少我找不到关于它的任何信息,这是我的问题
这是代码
arr = [1, True, 'a', 2]
print('a' in arr in arr) # prints False
print(('a' in arr) in arr) # prints True
我不了解的是第一张印刷品,我知道第二张印刷品中的第一张in
返回True
,然后它检查True
是否为in arr
,但是第一张印刷品呢?它会检查'a'
是in arr
,然后是arr
是in arr
吗?
前提为假;可以链接in
运算符 .请参阅文档中的比较:
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"
因此,就像其他任何链式比较一样,a in b in c
等同于(a in b) and (b in c)
(除了b
仅被评估一次.
'a' in arr in arr
为假的原因是arr in arr
为假.唯一一次x in x
为true的情况是,如果x是对__contains__
进行子字符串比较的类型(例如str
或bytes
),或者它是实际上包含自身的容器(例如lst = []; lst.append(lst)
). >
As far as I know, the in
operator in Python can't be chained or at least I couldn't find any info on it, here is my problem
Here is the code
arr = [1, True, 'a', 2]
print('a' in arr in arr) # prints False
print(('a' in arr) in arr) # prints True
What I don't understand is the first print, I know in the second the first in
returns True
and then it check if True
is in arr
, but what about the first one? Does it check if 'a'
is in arr
and then if arr
is in arr
?
The premise is false; the in
operator can be chained. See Comparisons in the docs:
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"
So, just as with any other chained comparison, a in b in c
is equivalent to (a in b) and (b in c)
(except that b
is only evaluated once.
The reason 'a' in arr in arr
is false is that arr in arr
is false. The only time x in x
is true is if x is type that does substring comparisons for __contains__
(like str
or bytes
), or if it's a container that actually contains itself (like lst = []; lst.append(lst)
).
这篇关于in运算符链接产生意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!