【问题标题】:What's more efficient in Python: `key not in list` or `not key in list`? [duplicate]在 Python 中什么更有效:`key not in list` 或 `not key in list`? [复制]
【发布时间】:2019-02-02 13:02:18
【问题描述】:

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

哪个更有效率?

element not in list

或者:

not element in list

?

【问题讨论】:

  • 为什么只有这些,?,可能像(a is not Nonenot a is None)等。

标签: python sequence contains in-operator not-operator


【解决方案1】:

它们的行为相同,以至于产生相同的字节码;它们同样有效。也就是说,element not in list 通常被认为是首选。 PEP8 没有针对not ... in... not in 的具体建议,但它针对not ... is... is notit 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

【讨论】:

    【解决方案2】:

    当你在做的时候:

    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

    【讨论】:

    • @Downvoter 为什么要投反对票
    • 我没有投反对票,但是您自己的链接显示字节码是相同的,所以...
    • @juanpa.arrivillaga 这是真的,对不起,?
    猜你喜欢
    • 2018-02-22
    • 2018-10-14
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    相关资源
    最近更新 更多