使用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()
函数,它使对象的非浅层副本。
谢谢。有用。你能解释一下发生了什么吗?有什么区别? –
@ lostboy_19我在答案中添加了解释。 –
y = list(x)更容易理解与y = x相同的语法[:] –