在Python中,'e in c'与'e not in c'不同吗?

时间:2012-10-17 18:53:27

标签: python

  

可能重复:
  Order of syntax for using ‘not’ and ‘in’ keywords

我的TA声称e not in c并不总是产生与not e in c相同的结果(他没有给出解释为什么)。我从来没有亲自在任何人的代码中看过第二种形式(除了他和书籍解释说这两个 相当)并且从未见过两者在行为上有所不同,所以我对这种说法持怀疑态度。我没有通过谷歌找到任何东西,我决定来这里。

所有人都有关于两者行为不同的任何情况的任何信息吗?

2 个答案:

答案 0 :(得分:26)

它们完全相同,因为两者实际上都应用了not in比较:

In [25]: def func():
    'e' not in 'bee'
   ....:     
   ....:     

In [27]: def func1():
    not 'e' in 'bee'
   ....:     
   ....:     
In [29]: dis.dis(func)
  2           0 LOAD_CONST               1 ('e')
              3 LOAD_CONST               2 ('bee')
              6 COMPARE_OP               7 (not in)
              9 POP_TOP             
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE        

In [30]: dis.dis(func1)
  2           0 LOAD_CONST               1 ('e')
              3 LOAD_CONST               2 ('bee')
              6 COMPARE_OP               7 (not in)
              9 POP_TOP             
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE  

答案 1 :(得分:2)

他们是完全相同的。 not的优先级低于in,因此not x in y会被解析为not (x in y),其返回in的反面,not in确实