Python 参考资料

发布于 2024-08-31 20:08:02 字数 221 浏览 5 评论 0原文

有人可以解释为什么整数示例会导致 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

凑诗 2024-09-07 20:08:02

因为整数是不可变的,而列表是可变的。从语法上就可以看出。在 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 to x (it is alone on the LHS). In x[0] = 4, you're calling the index operator on the list and giving it a parameter - it's actually equivalent to x.__setitem__(0, 4), which is obviously changing the original object, not creating a new one.

念﹏祤嫣 2024-09-07 20:08:02

如果您执行y = x,则 y 和 x 是对同一对象的引用。但整数是不可变的,当你执行x + 1时,会创建新的整数:

>>> x = 1
>>> id(x)
135720760
>>> x += 1
>>> id(x)
135720748
>>> x -= 1
>>> id(x)
135720760

当你有一个可变对象(例如列表、自己定义的类)时,每当 y 更改时 x 也会更改,因为它们指向单个对象。

If you do y = x, y and x are the reference to the same object. But integers are immutable and when you do x + 1, the new integer is created:

>>> x = 1
>>> id(x)
135720760
>>> x += 1
>>> id(x)
135720748
>>> x -= 1
>>> id(x)
135720760

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.

北座城市 2024-09-07 20:08:02

这是因为当你在 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.

晚雾 2024-09-07 20:08:02

正如前面的答案所说,您编写的代码将同一对象分配给不同的名称(例如别名)。
如果要将原始列表的副本分配给新变量(实际上是对象)
使用这个解决方案:

>>> x=[1,2,3]
>>> y=x[:] #this makes a new list
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
>>> x[0]=4
>>> x
[4, 2, 3]
>>> y
[1, 2, 3]

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:

>>> x=[1,2,3]
>>> y=x[:] #this makes a new list
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
>>> x[0]=4
>>> x
[4, 2, 3]
>>> y
[1, 2, 3]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文