【发布时间】:2013-08-29 04:12:35
【问题描述】:
我正在从一个列表中插入和删除元素,该列表是从另一个列表中复制的,我希望保持不变。但是,将操作应用到前者之后,后面的结果也发生了变化。我怎样才能避免这种情况?
这是正在发生的事情的一个例子:
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]
我不明白为什么该操作会在父列表中传播。我怎样才能避免这种情况?我应该将列表保存为排列,还是应该使用循环创建列表副本?
【问题讨论】:
标签: python list parent operation propagation