在这篇文章中,我们将看到 != (不等于) 操作符。在 Python 中 != 被定义为不等于运算符。如果两边的操作数不相等,它返回True,如果相等,则返回False。而is not运算符检查两个对象的id()是否相同。如果相同,则返回False,如果不相同,则返回True。而is not运算符如果两边的操作数不相等,则返回True,如果相等则返回False

让我们逐一理解这些概念。

示例1:

a = 10
b = 10

print(a is not b)
print(id(a), id(b))

c = "yiibai"\\nd = "yiibai"\\nprint(c is not d)
print(id(c), id(d))

e = [1,2,3,4]
f = [1,2,3,4]
print(e is not f)
print(id(e), id(f))

运行结果:

False
140737220702240 140737220702240
False
2781854910648 2781854910648
True
2781854458376 2781854458440

运行结果解释说明:

  • 首先,整数数据的输出是错误的,因为变量a,b都是指同一数据10。
  • 其次,对于字符串数据,输出结果是错误的,因为变量c,d指的是同一个数据 “Python”。
  • 第三,对于列表数据,输出为真,因为变量e,f有不同的内存地址。

示例2:

!= 被定义为不等于运算符。如果两边的操作数互不相等,则返回 “True”;如果相等,则返回 “False”。


a = 10
b = 10
print(a != b)
print(id(a), id(b))

c = "yiibai"\\nd = "yiibai"\\nprint(c != d)
print(id(c), id(d))

e = [ 1, 2, 3, 4]
f=[ 1, 2, 3, 4]
print(e != f)
print(id(e), id(f))

运行结果:

False
140737220702240 140737220702240
False
2001874929848 2001874929848
False
2001874477576 2001874477640

示例3:

!= 操作符比较两个对象的值或相等,而 Python is not 操作符检查两个变量是否指向内存中的同一个对象。


list1 = []
list2 = []
list3 = list1

#First if
if (list1 != list2):
    print(" First if Condition True")
else:
    print("First else Condition False")

#Second if
if (list1 is not list2):
    print("Second if Condition True")
else:
    print("Second else Condition False")

#Third if
if (list1 is not list3):
    print("Third if Condition True")
else:
    print("Third else Condition False")

list3 = list3 + list2

#Fourth if
if (list1 is not list3):
    print("Fourth if Condition True")
else:
    print("Fourth else Condition False")

运行结果:

First else Condition False
Second if Condition True
Third else Condition False
Fourth if Condition True

运行结果解释说明:

  • 第一个如果条件的输出是 False,因为list1list2都是空列表。
  • 第二个如果条件显示 True",因为两个空列表在不同的内存位置。因此 list1list2 指的是不同的对象。可以用 python 中的 id() 函数来检查,它返回一个对象的 “身份”。
  • 如果条件是 “False“,第三个输出是 “False“,因为 list1list3 都指向同一个对象。
  • 如果条件是 “True“,则第四个输出,因为两个列表的连接总是产生一个新的列表。