在Python中,更有效的方法是:“键不在列表中”或“键不在列表中”? [英] What's more efficient in Python: `key not in list` or `not key in list`?

查看:107
本文介绍了在Python中,更有效的方法是:“键不在列表中”或“键不在列表中”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是发现这两种语法方法都是有效的。

Just found out that both syntax ways are valid.

哪个效率更高?

element not in list

或:

not element in list

吗?

推荐答案

它们的行为相同,甚至产生相同的字节码;它们同样有效。也就是说,通常将不在列表中的元素。 PEP8对 not ... in ... not 并没有具体的建议,但是不是...是而不是 ...不是它更喜欢后者

They behave identically, to the point of producing identical byte code; they're equally efficient. That said, element not in list is usually considered preferred. PEP8 doesn't have a specific recommendation on not ... in vs. ... not in, but it does for not ... is vs. ... is not, and it prefers the latter:


使用不是运算符,而不是 not ...是。虽然这两个表达式在功能上相同,但前者更具可读性和首选性。

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

要显示性能上的等效性,请执行快速字节码检查:

To show equivalence in performance, a quick byte code inspection:

>>> 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

这篇关于在Python中,更有效的方法是:“键不在列表中”或“键不在列表中”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆