之前可能会问过,但搜索起来很困难。基本上我想知道如何制作一个列表副本,列表更改时不会更新。我已经在Python中使用了一段时间了 - 这是我第一次遇到这个问题。
var = 10
varcopy = var
for i in range(0,5):
var = var + i
print var
print varcopy
10
10
11
10
13
10
16
10
20
list = []
listcopy = list
for i in range(0,5):
list.append(i)
print list
print listcopy
[0]
[0]
[0, 1]
[0, 1]
[0, 1, 2]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
为什么列表副本还要附加到?!如何冻结它以获得:
[0]
[]
[0, 1]
[]
[0, 1, 2]
[]
[0, 1, 2, 3]
等...
答案 0 :(得分:1)
list
和listcopy
都指向同一个对象。以下是制作列表副本的一些方法:
listcopy = list[:]
import copy
listcopy = copy.copy(list)
# Also make a copy of the objects in the list
import copy
listcopy = copy.deepcopy(list)