【发布时间】:2019-02-02 13:02:18
【问题描述】:
刚刚发现两种语法方式都有效。
哪个更有效率?
element not in list
或者:
not element in list
?
【问题讨论】:
-
为什么只有这些,?,可能像(
a is not None或not a is None)等。
标签: python sequence contains in-operator not-operator
刚刚发现两种语法方式都有效。
哪个更有效率?
element not in list
或者:
not element in list
?
【问题讨论】:
a is not None 或not a is None)等。
标签: python sequence contains in-operator not-operator
它们的行为相同,以至于产生相同的字节码;它们同样有效。也就是说,element not in list 通常被认为是首选。 PEP8 没有针对not ... in 与... not in 的具体建议,但它针对not ... is 与... is not 和it prefers the latter 有具体建议:
使用
is not运算符而不是not ... is。虽然这两个表达式在功能上是相同的,但前者更易读,更受欢迎。
为了显示性能等效,快速字节码检查:
>>> 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
如果x在y中,则基本上会简化为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 基本上只是反其道而行之(如果某事为真,则不会使其为假,与相反的观点相同
【讨论】: