【发布时间】:2019-08-04 23:08:30
【问题描述】:
l1=[1,2,3]
l2=[1,2,3]
print(l1 is l2)
# False
谁能解释这段代码。为什么是假的?
【问题讨论】:
-
您可以将其视为实例比较。它是完全相同的对象吗?不仅仅是内容。
-
Python
is总是检查对象身份,==通常检查对象平等。
标签: python
l1=[1,2,3]
l2=[1,2,3]
print(l1 is l2)
# False
谁能解释这段代码。为什么是假的?
【问题讨论】:
is 总是检查对象身份,== 通常检查对象平等。
标签: python
is 运算符检查两个操作数是否引用同一个对象。在这个 l1 和 l2 是两个不同的对象,所以,它返回 False。
请注意,两个列表实例不会仅仅因为它们具有相同的内容而引用同一个对象。
您可以使用id 检查两者是否引用同一个对象。检查下面的代码。在这种情况下,您可以看到l1 和l2 是不同的对象,而l2 和l3 指的是同一个对象。请注意以下代码中== 运算符的使用以及如果列表的内容相同,它如何返回True。
l1=[1,2,3]
l2=[1,2,3]
l3 = l2
print("l1 = %s" %(id(l1)))
print("l2 = %s" %(id(l2)))
print("l3 = %s" %(id(l3)))
print(l1 is l2)
print(l2 is l3)
print(l1 == l2)
print(l2 == l3)
输出:
l1 = 139839807952728
l2 = 139839807953808
l3 = 139839807953808
False
True
True
True
注意:如果要根据内容比较两个对象,请使用== 运算符
【讨论】:
is:测试两个变量是否指向同一个对象,而不是两个变量具有相同的值。
# - Darling, I want some pudding!
# - There is some in the fridge.
pudding_to_eat = fridge_pudding
pudding_to_eat is fridge_pudding
# => True
# - Honey, what's with all the dirty dishes?
# - I wanted to eat pudding so I made some. Sorry about the mess, Darling.
# - But there was already some in the fridge.
pudding_to_eat = make_pudding(ingredients)
pudding_to_eat is fridge_pudding
# => False
【讨论】:
所以== 运算符比较两个对象或变量的值,is 运算符检查比较的对象是否相同。你可以把它想象成比较pointers。
【讨论】: