python - 了解 "is"运算符

标签 python operators

The is operator does not match the values of the variables, but the instances themselves.

这到底是什么意思?

我声明了两个名为 xy 的变量在两个变量中分配了相同的值,但是当我使用 is 运算符时它返回 false .

我需要澄清一下。这是我的代码。

x = [1, 2, 3]
y = [1, 2, 3]

print(x is y)  # It prints false!

最佳答案

您误解了 is 运算符测试的内容。它测试两个变量是否指向相同的对象,而不是两个变量是否具有相同的值。

来自 is operator 的文档:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

请改用 == 运算符:

print(x == y)

这将打印 Truexy 是两个 独立的 列表:

x[0] = 4
print(y)  # prints [1, 2, 3]
print(x == y)   # prints False

如果你使用 id() function 你会看到 xy 有不同的标识符:

>>> 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/

相关文章:

python - Instapy 错误与 smart_run 第 117 行导致失败

python - 这个python表达式是什么意思

c# - 运算符 '??' 不能应用于类型 'string' 和 'System.DBNull' 的操作数

python - 使用正则表达式解析类似 xml 的文档

python - 使用查找器的正则表达式

python - 欺骗Python运算符优先级

c++ - 当我插入 map c++​​ 时,为什么不调用小于运算符?

python - 和 Python 列表上的运算符

c - C 中的运算符 &= 和 ~1U

python - TimeDistributed 一次多个层