in运算符链接产生意外结果 [英] Unexpected result with `in` operator chaining

查看:107
本文介绍了in运算符链接产生意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,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,然后是arrin 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__进行子字符串比较的类型(例如strbytes),或者它是实际上包含自身的容器(例如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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆