本文介绍了在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:
要显示性能上的等效性,请执行快速字节码检查:
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中,更有效的方法是:“键不在列表中”或“键不在列表中”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!