Python if not == vs if != [英] Python if not == vs if !=
问题描述
这两行代码有什么区别:
如果不是 x == 'val':
和
如果 x != 'val':
一种比另一种更有效吗?
使用会更好吗
如果 x == 'val':经过别的:
使用 dis
查看两个版本生成的字节码:
not ==
4 0 LOAD_FAST 0 (foo)3 LOAD_FAST 1(条形)6 COMPARE_OP 2 (==)9 UNARY_NOT10 RETURN_VALUE
!=
4 0 LOAD_FAST 0 (foo)3 LOAD_FAST 1(条形)6 COMPARE_OP 3 (!=)9 RETURN_VALUE
后者操作较少,因此效率可能稍高一些.
<小时>在评论中指出(谢谢,<一个 href="https://stackoverflow.com/users/1896169/quincunx">@Quincunx) 那里你有 if foo != bar
与 if not foo== bar
操作次数完全一样,只是COMPARE_OP
变了,POP_JUMP_IF_TRUE
变成了POP_JUMP_IF_FALSE
:
not ==
:
2 0 LOAD_FAST 0 (foo)3 LOAD_FAST 1(条形)6 COMPARE_OP 2 (==)9 POP_JUMP_IF_TRUE 16
!=
2 0 LOAD_FAST 0 (foo)3 LOAD_FAST 1(条形)6 COMPARE_OP 3 (!=)9 POP_JUMP_IF_FALSE 16
在这种情况下,除非每次比较所需的工作量不同,否则您根本看不到任何性能差异.
<小时>但是,请注意,这两个版本在逻辑上并不总是相同,因为这取决于 __eq__
和 __ne__
的实现对于有问题的对象.根据数据模型文档:
比较运算符之间没有隐含的关系.这x==y
的真实性并不意味着 x!=y
是错误的.
例如:
<预><代码>>>>类虚拟(对象):def __eq __(自己,其他):返回真def __ne__(自我,其他):返回真>>>not Dummy() == Dummy()错误的>>>假人() !=假人()真的<小时>
最后,也许是最重要的:一般来说,如果两个 在逻辑上相同,x != y
比 not 更具可读性x == y
.
What is the difference between these two lines of code:
if not x == 'val':
and
if x != 'val':
Is one more efficient than the other?
Would it be better to use
if x == 'val':
pass
else:
Using dis
to look at the bytecode generated for the two versions:
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.
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 ==
:
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.
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:
There are no implied relationships among the comparison operators. The truth of
x==y
does not imply thatx!=y
is false.
For example:
>>> class Dummy(object):
def __eq__(self, other):
return True
def __ne__(self, other):
return True
>>> not Dummy() == Dummy()
False
>>> Dummy() != Dummy()
True
Finally, and perhaps most importantly: in general, where the two are logically identical, x != y
is much more readable than not x == y
.
这篇关于Python if not == vs if !=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!