The
is
operator does not match the values of the variables, but the instances themselves.
这到底是什么意思?
我声明了两个名为 x
和 y
的变量在两个变量中分配了相同的值,但是当我使用 is
运算符时它返回 false .
我需要澄清一下。这是我的代码。
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # It prints false!
最佳答案
您误解了 is
运算符测试的内容。它测试两个变量是否指向相同的对象,而不是两个变量是否具有相同的值。
来自 is
operator 的文档:
The operators
is
andis not
test for object identity:x is y
is true if and only ifx
andy
are the same object.
请改用 ==
运算符:
print(x == y)
这将打印 True
。 x
和 y
是两个 独立的 列表:
x[0] = 4
print(y) # prints [1, 2, 3]
print(x == y) # prints False
如果你使用 id()
function 你会看到 x
和 y
有不同的标识符:
>>> id(x)
4401064560
>>> id(y)
4401098192
但如果你将 y
分配给 x
那么两者都指向同一个对象:
>>> x = y
>>> id(x)
4401064560
>>> id(y)
4401064560
>>> x is y
True
和 is
表明两者是同一个对象,它返回 True
。
请记住,在 Python 中,names are just labels referencing values ;您可以有多个名称指向同一个对象。 is
告诉您两个名称是否指向同一个对象。 ==
告诉您两个名称是否指代具有相同值的对象。
关于python - 了解 "is"运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13650293/