Python 不等於運算子

Python 不等運算子返回 True 如果兩個變數是相同類型且具有不同值,如果值相同則返回 False。 Python 是動態且強類型的語言,因此如果兩個變數具有相同的值但它們的類型不同,則不等運算子將返回 True

Python 不等運算子

Operator Description
!= Not Equal operator, works in both Python 2 and Python 3.
<> Not equal operator in Python 2, deprecated in Python 3.

Python 2 示例

讓我們看一些 Python 2.7 中的不等運算子示例。

$ python2.7
Python 2.7.10 (default, Aug 17 2018, 19:45:58) 
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 10 <> 20
True
>>> 10 <> 10
False
>>> 10 != 20
True
>>> 10 != 10
False
>>> '10' != 10
True
>>> 

Python 3 示例

這裡是一些 Python 3 控制台示例。

$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 10 <> 20
  File "<stdin>", line 1
    10 <> 20
        ^
SyntaxError: invalid syntax
>>> 10 != 20
True
>>> 10 != 10
False
>>> '10' != 10
True
>>> 

如果您使用的是 Python 3.6 或更高版本,我們也可以使用 Python 不等運算子與 f-strings

x = 10
y = 10
z = 20

print(f'x is not equal to y = {x!=y}')

flag = x != z
print(f'x is not equal to z = {flag}')

# python is strongly typed language
s = '10'
print(f'x is not equal to s = {x!=s}')

输出:

x is not equal to y = False
x is not equal to z = True
x is not equal to s = True

Python 不等於自定義物件

當我們使用不等於運算子時,它會呼叫 __ne__(self, other) 函數。因此,我們可以定義我們自己的物件實作並改變自然輸出。假設我們有一個包含字段 – id 和 record 的 Data 類別。當我們使用不等於運算子時,我們只想比較它的記錄值。我們可以通過實現我們自己的 __ne__() 函數來實現這一點。

class Data:
    id = 0
    record = ''

    def __init__(self, i, s):
        self.id = i
        self.record = s

    def __ne__(self, other):
        # 如果類型不同則返回 true
        if type(other) != type(self):
            return True
        if self.record != other.record:
            return True
        else:
            return False


d1 = Data(1, 'Java')
d2 = Data(2, 'Java')
d3 = Data(3, 'Python')

print(d1 != d2)
print(d2 != d3)

輸出:

False
True

請注意,d1 和 d2 的記錄值相同,但“id”不同。如果我們刪除 __ne__() 函數,則輸出將如下所示:

True
True

您可以從我們的 GitHub 存儲庫 檢查完整的 Python 腳本和更多 Python 示例。

Source:
https://www.digitalocean.com/community/tutorials/python-not-equal-operator