Python 参考资料
有人可以解释为什么整数示例会导致 x 和 y 产生不同的值,而列表示例会导致 x 和 y 是同一个对象吗?
x = 42
y = x
x = x + 1
print x # 43
print y # 42
x = [ 1, 2, 3 ]
y = x
x[0] = 4
print x # [4, 2, 3]
print y # [4, 2, 3]
x is y # True
Can someone explain why the example with integers results in different values for x and y and the example with the list results in x and y being the same object?
x = 42
y = x
x = x + 1
print x # 43
print y # 42
x = [ 1, 2, 3 ]
y = x
x[0] = 4
print x # [4, 2, 3]
print y # [4, 2, 3]
x is y # True
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为整数是不可变的,而列表是可变的。从语法上就可以看出。在 x = x + 1 中,您实际上为 x 分配了一个新值(它单独位于 LHS 上)。在 x[0] = 4 中,您调用列表上的索引运算符并为其提供一个参数 - 它实际上相当于 x.__setitem__(0, 4) ,这显然是在改变原始对象,而不是创建一个新对象。
Because integers are immutable, while list are mutable. You can see from the syntax. In
x = x + 1
you are actually assigning a new value tox
(it is alone on the LHS). Inx[0] = 4
, you're calling the index operator on the list and giving it a parameter - it's actually equivalent tox.__setitem__(0, 4)
, which is obviously changing the original object, not creating a new one.如果您执行
y = x
,则 y 和 x 是对同一对象的引用。但整数是不可变的,当你执行x + 1
时,会创建新的整数:当你有一个可变对象(例如列表、自己定义的类)时,每当 y 更改时 x 也会更改,因为它们指向单个对象。
If you do
y = x
, y and x are the reference to the same object. But integers are immutable and when you dox + 1
, the new integer is created:When you have a mutable object (e.g. list, classes defined by yourself), x is changed whenever y is changed, because they point to a single object.
这是因为当你在 python 中拥有一个列表或一个元组时,你就创建了一个对象的引用。
当你说 y = x 时,你用 y 引用了与 x 相同的对象。
所以当你编辑对象时xy也会随之改变。
That's because when you have a list or a tuple in python you create a reference to an object.
When you say that y = x you reference to the same object with y as x does.
So when you edit the object of x y changes with it.
正如前面的答案所说,您编写的代码将同一对象分配给不同的名称(例如别名)。
如果要将原始列表的副本分配给新变量(实际上是对象)
使用这个解决方案:
As the previous answers said the code you wrote assigns the same object to different names such aliases.
If you want to assign a copy of the original list to the new variable (object actually)
use this solution: