有人能解释一下列表中is操作符的工作机制吗?

2024-04-23 23:13:20 发布

您现在位置:Python中文网/ 问答频道 /正文

l1=[1,2,3]
l2=[1,2,3]
print(l1 is l2)
# False

有人能解释这段代码吗。为什么是假的?你知道吗


Tags: 代码falsel1isprintl2
3条回答

is:测试两个变量是否指向同一对象,而不是两个变量是否具有相同的值。你知道吗

Nicely put:

# - 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运算符检查两个操作数是否引用同一对象。在这种情况下,l1和l2是两个不同的对象,因此,它返回False。你知道吗

请注意,两个列表实例引用同一对象并不是因为它们具有相同的内容。你知道吗

您可以使用id检查两者是否引用同一对象。检查以下代码。在本例中,您可以看到l1l2是不同的对象,而l2l3是指同一个对象。请注意,在下面的代码中使用==运算符,以及如果列表的内容相同,它如何返回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运算符检查比较的对象是否相同。你可以把它想象成比较pointers。你知道吗

相关问题 更多 >