"not ==" 和 "!=" 有什么区别?
What is the difference between "not ==" and "!="?
我正在查看 google,但找不到答案。
if 5 != 10:
print('True')
# True
if not 5 == 10:
print('True')
# True
两者似乎都一样。何时使用 "not ==" 何时使用 "!="?
在比较两个整数的情况下,它们是相同的。更喜欢 !=
,因为它更像 pythonic。
如果任一 操作数是自定义class 的实例,结果可能会有所不同。自定义 classes 可以独立地覆盖 ==
和 !=
运算符(即使结果很疯狂)
来自左侧:
>>> 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
只要 ==
return 是 !=
的逻辑逆,这些语句就等价。对于大多数数据类型,这是一个有效的假设,但是 Python 允许具体实现 ==
和 !=
(__eq__
for ==
and __ne__
用于 !=
)。所以这实际上取决于您使用的数据类型。
而==
和!=
甚至可能不是return布尔值,它们甚至不必return相同的数据类型。这开启了另一种自定义结果的可能性:通过 truth value testing, which can be customized (besides others) by the __bool__
(或 Python 2 中的 __nonzero
)方法。
但是对于整数,您的两种方法是等效的。但是我总是使用 !=
方法。意图更清晰,更简短。
只是为了给你一个语句不等价的例子,让我们采用一种数据类型,例如实现 ==
和 !=
到 return 另一个包含布尔值的 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
中使用其中任何一个,两者都会引发异常。
正如您从结果中看到的那样,两者的意思相同,检查一个值是否与另一个不同,这是一个偏好问题...
我正在查看 google,但找不到答案。
if 5 != 10:
print('True')
# True
if not 5 == 10:
print('True')
# True
两者似乎都一样。何时使用 "not ==" 何时使用 "!="?
在比较两个整数的情况下,它们是相同的。更喜欢 !=
,因为它更像 pythonic。
如果任一 操作数是自定义class 的实例,结果可能会有所不同。自定义 classes 可以独立地覆盖 ==
和 !=
运算符(即使结果很疯狂)
来自左侧:
>>> 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
只要 ==
return 是 !=
的逻辑逆,这些语句就等价。对于大多数数据类型,这是一个有效的假设,但是 Python 允许具体实现 ==
和 !=
(__eq__
for ==
and __ne__
用于 !=
)。所以这实际上取决于您使用的数据类型。
而==
和!=
甚至可能不是return布尔值,它们甚至不必return相同的数据类型。这开启了另一种自定义结果的可能性:通过 truth value testing, which can be customized (besides others) by the __bool__
(或 Python 2 中的 __nonzero
)方法。
但是对于整数,您的两种方法是等效的。但是我总是使用 !=
方法。意图更清晰,更简短。
只是为了给你一个语句不等价的例子,让我们采用一种数据类型,例如实现 ==
和 !=
到 return 另一个包含布尔值的 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
中使用其中任何一个,两者都会引发异常。
正如您从结果中看到的那样,两者的意思相同,检查一个值是否与另一个不同,这是一个偏好问题...