首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python中" in“的结合性?

Python中" in“的结合性?
EN

Stack Overflow用户
提问于 2012-09-30 19:24:53
回答 1查看 4.2K关注 0票数 109

我正在做一个Python解析器,这真的让我很困惑:

代码语言:javascript
复制
>>> 1 in [] in 'a'
False

>>> (1 in []) in 'a'
TypeError: 'in <string>' requires string as left operand, not bool

>>> 1 in ([] in 'a')
TypeError: 'in <string>' requires string as left operand, not list

in在Python语言中到底是如何工作的,比如结合性等?

为什么这两个表达式的行为方式不同?

EN

回答 1

Stack Overflow用户

发布于 2012-09-30 19:42:00

Python通过链式比较来做一些特殊的事情。

以下内容的评估方式有所不同:

代码语言:javascript
复制
x > y > z   # in this case, if x > y evaluates to true, then
            # the value of y is used, again, and compared with z

(x > y) > z # the parenthesized form, on the other hand, will first
            # evaluate x > y. And, compare the evaluated result
            # with z, which can be "True > z" or "False > z"

不过,在这两种情况下,如果第一个比较结果是False,则不会查看语句的其余部分。

对于你的特殊情况,

代码语言:javascript
复制
1 in [] in 'a'   # this is false because 1 is not in []

(1 in []) in a   # this gives an error because we are
                 # essentially doing this: False in 'a'

1 in ([] in 'a') # this fails because you cannot do
                 # [] in 'a'

此外,为了演示上面的第一条规则,这些语句的计算结果为True。

代码语言:javascript
复制
1 in [1,2] in [4,[1,2]] # But "1 in [4,[1,2]]" is False

2 < 4 > 1               # and note "2 < 1" is also not true

Python运算符的优先级:https://docs.python.org/3/reference/expressions.html#comparisons

票数 24
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12660870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档