我正在查看谷歌,但找不到答案。
if 5 != 10:
print('True')
# True
if not 5 == 10:
print('True')
# True
两者似乎都做同样的事情。什么时候用“
not ==
”,什么时候用“!=
”?
只要
==
返回 !=
的逻辑逆,这些语句是等效的。对于大多数数据类型来说,这是一个有效的假设,但是 Python 允许专门实现 ==
和 !=
(__eq__
表示 ==
和 __ne__
表示 !=
)。所以这实际上取决于您使用的数据类型。
并且
==
和 !=
甚至可能不返回布尔值,它们甚至不必返回相同的数据类型。这开辟了另一种定制结果的可能性:通过真值测试,可以通过__bool__
(或Python 2中的__nonzero
)方法进行定制(除了其他)。
但是对于整数,两种方法都是等效的。不过我总是会使用
!=
方法。意图更清晰,也更短。
只是为了给您提供一个语句不等效的示例,让我们采用一种数据类型,例如 NumPy 数组(只是为了命名以不同方式实现运算符的流行数据结构),它实现
==
和 !=
返回另一个 NumPy包含布尔值的数组,还实现了 __bool__
来抛出异常:
>>> import numpy as np
>>> np.array([1,2,3]) != np.array([3,3,3])
array([ True, True, False])
>>> not np.array([1,2,3]) == np.array([3,3,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
但是,如果您在
if
中使用其中任何一个,都会引发异常。
在比较两个整数的情况下,它们是相同的。 更喜欢
!=
,因为更Pythonic。
如果任一操作数是自定义类的实例,结果可能会有所不同。 自定义类可以独立地覆盖
==
和 !=
运算符(即使结果疯狂)
来自 LHS:
>>> class A:
... def __eq__(self, other):
... return False
... def __ne__(self, other):
... return False
...
>>> a = A()
>>> a != 5
False
>>> not a == 5
True
来自皇家园艺学会:
>>> class R(str):
... def __eq__(self, other):
... return False
... def __ne__(self, other):
... return False
...
>>> r = R()
>>> 'spam' != r
False
>>> not 'spam' == r
True
正如您从结果中看到的,两者的含义相同,检查一个值是否与另一个值不同,这是一个偏好问题...