我正在做一个Python解析器,这真的让我很困惑:
>>> 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语言中到底是如何工作的,比如结合性等?
为什么这两个表达式的行为方式不同?
发布于 2012-09-30 19:42:00
Python通过链式比较来做一些特殊的事情。
以下内容的评估方式有所不同:
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
,则不会查看语句的其余部分。
对于你的特殊情况,
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。
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
https://stackoverflow.com/questions/12660870
复制相似问题