Python 中哪个更有效:`key not in list` 或 `not key in list`?

What's more efficient in Python: `key not in list` or `not key in list`?

刚刚发现两种语法方式都有效。

哪个效率更高?

element not in list

或者:

not element in list

?

它们的行为相同,以至于生成相同的字节码;他们同样高效。也就是说,element not in list 通常被认为是首选。 PEP8 没有针对 not ... in... not in 的具体建议,但它针对 not ... is... is notit prefers the latter:

Use is not operator rather than not ... is. While both expressions are functionally identical, the former is more readable and preferred.

为了显示性能的等效性,快速检查字节码:

>>> import dis
>>> dis.dis('not x in y')
  1           0 LOAD_NAME                0 (x)
              2 LOAD_NAME                1 (y)
              4 COMPARE_OP               7 (not in)
              6 RETURN_VALUE

>>> dis.dis('x not in y')
  1           0 LOAD_NAME                0 (x)
              2 LOAD_NAME                1 (y)
              4 COMPARE_OP               7 (not in)
              6 RETURN_VALUE

当你在做的时候:

not x in y

而如果xy中,它基本上会简化为not True即:

>>> not True
False

另一方面,x not in y只是直接检查not in

查看时间(总是非常相似):

>>> import timeit
>>> timeit.timeit(lambda: 1 not in [1,2,3])
0.24575254094870047
>>> timeit.timeit(lambda: not 1 in [1,2,3])
0.23894292154022878
>>> 

顺便说一句,not 基本上只是做相反的事情(如果某件事是真的,不是会把它变成假的,相同点与相反点

not operator