这两行代码有什么区别:
if not x == 'val':
和
if x != 'val':
一个比另一个更有效吗?
使用会更好
if x == 'val':
pass
else:
最佳答案
使用 dis
查看为两个版本生成的字节码:
不是==
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
后者的操作较少,因此可能会稍微高效一些。
有人指出in the commments (谢谢, @Quincunx )你有 if foo != bar
与 if not foo == bar
的操作数完全相同,只是这样COMPARE_OP
改变并且 POP_JUMP_IF_TRUE
切换到 POP_JUMP_IF_FALSE
:
不是==
:
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
在这种情况下,除非每次比较所需的工作量有所不同,否则您根本不可能看到任何性能差异。
但是,请注意,两个版本在逻辑上并不总是相同,因为它取决于 __eq__
和 __ne__
的实现对于有问题的对象。根据 the data model documentation :
There are no implied relationships among the comparison operators. The truth of
x==y
does not imply thatx!=y
is false.
例如:
>>> class Dummy(object):
def __eq__(self, other):
return True
def __ne__(self, other):
return True
>>> not Dummy() == Dummy()
False
>>> Dummy() != Dummy()
True
最后,也许也是最重要的:一般来说,如果两个 在逻辑上相同,x != y
比 not 更易读x == y
.
关于Python if not == vs if !=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31026754/