[英]Copying arrays in python and manipulating one
我正在加载变量'x'
二维的文件“ data.imputation”。 变量'y'
是'x'
的副本。 我从'y'
弹出第一个数组(y是2D)。 为什么更改反映在x
? (还会弹出'x'
的第一个数组)
ip = open('data.meanimputation','r')
x = pickle.load(ip)
y = x
y.pop(0)
首先, len(x) == len(y)
。 即使在y.pop(0)
, len(x) == len(y)
。 这是为什么? 我该如何避免呢?
使用y = x[:]
代替y = x
。 y = x
表示y
和x
现在都指向同一对象。
看一下这个例子:
>>> x=[1,2,3,4]
>>> y=x
>>> y is x
True # it means both y and x are just references to a same object [1,2,3,4], so changing either of y or x will affect [1,2,3,4]
>>> y=x[:] # this makes a copy of x and assigns that copy to y,
>>> y is x # y & x now point to different object, so changing one will not affect the other.
False
如果x是一个列表,则为[:]
是没有用的:
>>> x= [[1,2],[4,5]]
>>> y=x[:] #it makes a shallow copy,i.e if the objects inside it are mutable then it just copies their reference to the y
>>> y is x
False # now though y and x are not same object but the object contained in them are same
>>> y[0].append(99)
>>> x
[[1, 2, 99], [4, 5]]
>>> y
[[1, 2, 99], [4, 5]]
>>> y[0] is x[0]
True #see both point to the same object
在这种情况下,您应该使用copy
模块的deepcopy()
函数,它会生成对象的非浅表副本。
y = x
不复制任何内容。 它将名称y
绑定到x
已经引用的同一对象。 分配裸名永远不会在Python中复制任何内容。
如果要复制对象,则需要使用要复制的对象可用的任何方法来显式复制它。 您没有说x
是什么类型的对象,因此无法说明如何复制它,但是copy
模块提供了一些适用于多种类型的功能。 另请参阅此答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.