在Python中,更有效的方法是:“键不在列表中”或“键不在列表中”? [英] What's more efficient in Python: `key not in list` or `not key in list`?
问题描述
只是发现这两种语法方法都是有效的。
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 thannot ... 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屋!