简体   繁体   English

将数组添加到数组而不影响数组中的元素

[英]add array to an array without affecting the elements in array

Iam a beginer in python.Iam trying to add an array in a list but when i update that array and again append it to the list the previous appended array is also updated.Why is it happening? 我是python的初学者,我试图在列表中添加一个数组,但是当我更新该数组并将其再次添加到列表中时,先前添加的数组也被更新了,为什么会这样?

list_of_sol=[]
a=[]
a.append(1)
list_of_sol.append(a)
a.append(2)
list_of_sol.append(a)
print list_of_sol

Output i was expecting was [[1],[1,2]] but output is [[1,2],[1,2]]. 我期望的输出为[[1],[1,2]],但输出为[[1,2],[1,2]]。

You are appending references to the list object a . 您要将引用附加到列表对象a This can be verified via id() of the two elements of the list. 可以通过列表中两个元素的id()进行验证。

>>> id(list_of_sol[1])
# 140477592091464
>>> id(list_of_sol[0])
# 140477592091464

So you end up appending two instances of a single object, rather than bare values. 因此,您最终将附加单个对象的两个实例,而不是附加裸值。 The expected behaviour can be realised using list_of_sol.append(list(a)) 可以使用list_of_sol.append(list(a))实现预期的行为

If you want the output you've said you expected, do it like this: 如果要获得您期望的输出,请按以下步骤进行:

list_of_sol=[]
a=[]
a.append(1)
list_of_sol.append(a[:])
a.append(2)
list_of_sol.append(a)
print list_of_sol

This may be about copy and deepcopy: list_of_sol.append(a) puts a copy of a in list_of_sol, and this copy list_of_sol[0] refer to the same place with a, you can use id(list_of_sol[0]) == id(a) test it You can check this : 这可能与复制和深度复制有关:list_of_sol.append(a)将a的副本放入list_of_sol中,并且此副本list_of_sol [0]与a指向同一位置,可以使用id(list_of_sol [0])== id (a)测试您可以检查一下:

from copy import deepcopy

list_of_sol=[]
a=[]
a.append(1)
list_of_sol.append(deepcopy(a[:])) #here changed
a.append(2)
list_of_sol.append(deepcopy(a)) #here changed
print list_of_sol

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM