引用列表对象的变量不同于(某些)其他对象? [英] Reference list object by a variable is different than for (some) other objects?

查看:74
本文介绍了引用列表对象的变量不同于(某些)其他对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在定义列表对象的变量时,例如:

In defining variable of a list object, for example:

x = [1,2,0.2,3,4]
y = x
x.sort()

我希望y仍然等于[1, 2, 0.2, 3, 4],但事实并非如此. y的值随着x的改变而改变.为了解决这个问题,我发现使用y = x.copy()可以保留第一行中的值.

I would expect that y is still equal to [1, 2, 0.2, 3, 4], but it does not. The value of y changed as x changed. To counter this, I found that using y = x.copy() can preserve the value in the first line.

另一方面,另一个示例:

On the other hand, another example :

x = 5
y = x
x = 4

由此y的值仍然是5,它不会随着x的变化而变化.

from this the value of y is still 5, it does not change as x change.

我的问题:这是由于list的类中的设计引起的,还是有另一种解释?我发现使用x.append(value)时也会发生动态变化.任何见解均表示赞赏.问候,自觉

My question : is this due to the design in list's class, or there is another explanation? I found the dynamic change also happen when using x.append(value). Any insight is appreciated. Regards, Arief

推荐答案

每个变量只是一个指向Python对象的指针,如果您有两个指向同一个对象的变量,那么您将看到它们中的每个更改(和.sort就地工作,如果要新的list,则应使用x = sorted(x)).但是,如果您重新分配变量,则它将指向另一个对象.

Every variable is just a pointer to an Python object, if you have two variables pointing to the same object then you'll see the changes in each of them (and .sort works in-place, if you want a new list you should use x = sorted(x)). However if you re-assign a variable then it will point to a different object.

我添加了一些图像以更好地可视化正在发生的事情(不是高质量的图像,但我希望它能传达信息).

I included some images to better visualize what's happening (not high-quality but I hope it conveys the message).

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

如果您copy(这是一个浅表副本,因此列表内容仍然引用相同的项!):

If you copy (it's a shallow copy so the list-contents still refer to the same items!):

x = [1,2,0.2,3,4]
y = x.copy()

您的第二种情况是相同的:

Your second case is just the same:

x = 5
y = x

但是随后您重新分配了变量x(因此此后它指向另一个对象):

But then you re-assign the variable x (so it points to another object thereafter):

x = 4

这篇关于引用列表对象的变量不同于(某些)其他对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆