Unexpected result with `in` operator chaining

南笙酒味 提交于 2020-03-09 05:27:15

问题


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?


回答1:


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)).



来源:https://stackoverflow.com/questions/50866585/unexpected-result-with-in-operator-chaining

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!