0

I am inserting and removing elements from a list that has been copied from another one I want to preserve unchanged. However, after applying the operations to the former, the later results also changed. How can I avoid that?

This is an example of what is happening:

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]

I do not understand why the operation propagates over the parent list. How can I avoid that? Should I save the list as an arrange, or should I create the list copy by using a loop?

4

3 回答 3

4

c = b[:]您需要使用或进行浅拷贝或深拷贝(如果需要递归复制内部对象)copy.deepcopy(b)。这样做c = b,只是创建了一个指向与 by 相同的对象的引用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]
于 2013-08-26T15:52:39.457 回答
3

你需要做一个深拷贝:

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

因为没有制作数组的副本,您只是创建了对数组的引用。以下是使用副本的方法:

http://docs.python.org/2/library/copy.html

于 2013-08-26T15:54:14.523 回答
0

利用

new_list = old_list[:]

或者

new_list = list(old_list)

如何克隆或复制列表?

于 2013-08-26T15:54:39.683 回答