Python中“in”的关联性?

我正在做一个Pythonparsing器,这让我困惑:

>>> 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中工作的,关于关联性等?

为什么这两个expression式中没有任何一个expression方式相同?

1 in [] in 'a'被评估为(1 in []) and ([] in 'a')

由于第一个条件( 1 in [] )为False ,整个条件评估为False ; ([] in 'a')从来没有实际评估过,所以不会引发错误。

这里是语句定义:

 In [121]: def func(): .....: return 1 in [] in 'a' .....: In [122]: dis.dis(func) 2 0 LOAD_CONST 1 (1) 3 BUILD_LIST 0 6 DUP_TOP 7 ROT_THREE 8 COMPARE_OP 6 (in) 11 JUMP_IF_FALSE 8 (to 22) #if first comparison is wrong #then jump to 22, 14 POP_TOP 15 LOAD_CONST 2 ('a') 18 COMPARE_OP 6 (in) #this is never executed, so no Error 21 RETURN_VALUE >> 22 ROT_TWO 23 POP_TOP 24 RETURN_VALUE In [150]: def func1(): .....: return (1 in []) in 'a' .....: In [151]: dis.dis(func1) 2 0 LOAD_CONST 1 (1) 3 LOAD_CONST 3 (()) 6 COMPARE_OP 6 (in) # perform 1 in [] 9 LOAD_CONST 2 ('a') # now load 'a' 12 COMPARE_OP 6 (in) # compare result of (1 in []) with 'a' # throws Error coz (False in 'a') is # TypeError 15 RETURN_VALUE In [153]: def func2(): .....: return 1 in ([] in 'a') .....: In [154]: dis.dis(func2) 2 0 LOAD_CONST 1 (1) 3 BUILD_LIST 0 6 LOAD_CONST 2 ('a') 9 COMPARE_OP 6 (in) # perform ([] in 'a'), which is # Incorrect, so it throws TypeError 12 COMPARE_OP 6 (in) # if no Error then # compare 1 with the result of ([] in 'a') 15 RETURN_VALUE 

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

以下是不同的评估:

 x > y > z # in this case, if x > y evaluates to true, then # the value of y is being used to compare, again, # to z (x > y) > z # the parenth 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运算符的优先级: http : //docs.python.org/reference/expressions.html#summary

从文档:

比较可以任意链接,例如,x <y <= z相当于x <y和y <= z,不同之处在于y只计算一次(但是在两种情况下,当x <y时都不计算z是假的)。

这意味着什么, x in y in z没有关联性!

以下是等同的:

 1 in [] in 'a' # <=> middle = [] # False not evaluated result = (1 in middle) and (middle in 'a') (1 in []) in 'a' # <=> lhs = (1 in []) # False result = lhs in 'a' # False in 'a' - TypeError 1 in ([] in 'a') # <=> rhs = ([] in 'a') # TypeError result = 1 in rhs 

简而言之,由于长期以来已经多次在这里以优秀的方式给出了布尔expression式是短路的 ,当通过进一步的评估来改变真假或者反之亦然时,已经停止了评估。

(见http://en.wikipedia.org/wiki/Short-circuit_evaluation

这可能有点短(没有双关语意思)作为答案,但如前所述,所有其他的解释在这里已经做得相当好,但我认为这个词应该被提及。