Python:操作意外地沿着父列表传播
我正在从一个列表中插入和删除元素,该列表是从另一个列表复制的,我希望保持不变。但是,在对前者应用这些操作之后,后面的结果也发生了变化。我怎样才能避免呢 这是正在发生的事情的一个例子:Python:操作意外地沿着父列表传播,python,list,parent,operation,propagation,Python,List,Parent,Operation,Propagation,我正在从一个列表中插入和删除元素,该列表是从另一个列表复制的,我希望保持不变。但是,在对前者应用这些操作之后,后面的结果也发生了变化。我怎样才能避免呢 这是正在发生的事情的一个例子: a = range(11) b = [] for i in a: b.append(i+1) print b #Out[10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] c = b # Here, what I expect is to safely save "b"
a = range(11)
b = []
for i in a:
b.append(i+1)
print b
#Out[10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
c = b
# Here, what I expect is to safely save "b" and work on its copy.
c.insert(-1,10.5)
print c
#Out[13]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10.5, 11]
c.remove(11)
print c
#Out[15]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10.5]
# So far everything is right: I inserted and removed what I wanted.
# But then, when I check on my "backed-up b", it has been modified:
print b
#Out[16]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10.5]
# On the other hand, "a" remains the same; it seems the propagation does not affect
# "loop-parenthood":
print a
# Out[17]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
我不明白为什么操作会在父列表上传播。我怎样才能避免呢?我应该将列表保存为排列,还是使用循环创建列表副本?您需要使用
c=b[:]
或copy.deepcopy(b)
创建浅拷贝或深拷贝(如果需要递归复制内部对象)。执行c=b
,只创建一个指向与b
相同对象的引用,因此,如果b
更改或c
更改,这两个变量都会反映这些更改
>>> a = range(11)
>>> b = []
>>> for i in a:
b.append(i+1)
>>> print b
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> c = b[:]
>>> c.insert(-1, 10.5)
>>> print c
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10.5, 11]
>>> c.remove(11)
>>> print c
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10.5]
>>> print b
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
您需要制作一个deepcopy:
import copy
a = range(11)
b = []
for i in a:
b.append(i+1)
print b
#Out[10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
c = copy.deepcopy(b)
# Here, what I expect is to safely save "b" and work on its copy.
c.insert(-1,10.5)
print c
#Out[13]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10.5, 11]
c.remove(11)
print c
#Out[15]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10.5]
# So far everything is right: I inserted and removed what I wanted.
# But then, when I check on my "backed-up b", it has been modified:
print b
#Out[16]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10.5]
# On the other hand, "a" remains the same; it seems the propagation do not affect
# "loop-parenthood":
print a
因为在不复制数组的情况下,您只是创建了对数组的引用。以下是如何使用复制:
使用
new_list = old_list[:]
或
太快了!谢谢。我只是在使用
c=b[:]
方法生成的表上运行了一个循环。迭代引用了两个表中的元素。最后不仅修改了c
,还修改了b
。然后我使用了c=copy.deepcopy(b)
方法,似乎应用于c
的循环只影响c
,而不影响b
。因此,只有这个方法对我正在执行的任务有用。@lag:您必须在其中包含列表或其他可变对象。对于您的示例,c=b[:]
方法应该非常有效。下一次,请考虑添加上下文,以便问题可以在这方面得到回答。只是在这里熟悉一下Python。对不起,我笨手笨脚。
new_list = list(old_list)