如果不是Python == vs if!= [英] Python if not == vs if !=
问题描述
这两行代码有什么区别:
What is the difference between these two lines of code:
if not x == 'val':
和
if x != 'val':
一个比另一个更有效吗?
Is one more efficient than the other?
如果x =='val',使用
Would it be better to use
if x == 'val':
pass
else:
推荐答案
使用 dis
查看为两个版本生成的字节码:
Using dis
to look at the bytecode generated for the two versions:
not ==
not ==
4 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 2 (==)
9 UNARY_NOT
10 RETURN_VALUE
!=
!=
4 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 3 (!=)
9 RETURN_VALUE
后者的操作较少,因此可能稍微提高效率。
The latter has fewer operations, and is therefore likely to be slightly more efficient.
有人指出在通讯中(谢谢, @Quincunx )在哪里你有如果foo!= bar
与如果不是foo == bar
操作次数完全相同,只是 COMPARE_OP
更改而 POP_JUMP_IF_TRUE
切换为 POP_JUMP_IF_FALSE
:
It was pointed out in the commments (thanks, @Quincunx) that where you have if foo != bar
vs. if not foo == bar
the number of operations is exactly the same, it's just that the COMPARE_OP
changes and POP_JUMP_IF_TRUE
switches to POP_JUMP_IF_FALSE
:
not ==
:
not ==
:
2 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 2 (==)
9 POP_JUMP_IF_TRUE 16
!=
!=
2 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 3 (!=)
9 POP_JUMP_IF_FALSE 16
在这种情况下,除非每次比较所需的工作量有所不同,否则您根本不会看到任何性能差异。
In this case, unless there was a difference in the amount of work required for each comparison, it's unlikely you'd see any performance difference at all.
但请注意,两个版本在逻辑上并不总是相同,因为它取决于 __ eq __ $ c $的实现对于有问题的对象,c>和
__ ne __
。根据数据模型文档:
However, note that the two versions won't always be logically identical, as it will depend on the implementations of __eq__
and __ne__
for the objects in question. Per the data model documentation:
比较运算符之间没有隐含的关系。
x == y
的
真值并不意味着x!= y
为假。
例如:
>>> class Dummy(object):
def __eq__(self, other):
return True
def __ne__(self, other):
return True
>>> not Dummy() == Dummy()
False
>>> Dummy() != Dummy()
True
最后,也许最重要的是:一般来说,两个在逻辑上相同的地方, x!= y
更多可读而不是x == y
。
Finally, and perhaps most importantly: in general, where the two are logically identical, x != y
is much more readable than not x == y
.
这篇关于如果不是Python == vs if!=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!