Kas*_*asa 4 python memory-management python-2.7
我似乎无法理解python中的以下行为:
x = [0, [1,2,3,4,5],[6]]
y = list(x)
y[0] = 10
y[2][0] = 7
print x
print y
Run Code Online (Sandbox Code Playgroud)
它输出:
[0, [1, 2, 3, 4, 5], [7]]
[10, [1, 2, 3, 4, 5], [7]]
Run Code Online (Sandbox Code Playgroud)
为什么x和y的第二个索引更新,只有y的第一个索引?
发生这种情况是因为list(x)
创建了列表的浅表副本x
.其中的一些元素x
是列表本身.没有为他们创建副本; 它们作为参考传递.以这种方式x
,y
最终得到与元素相同的列表的引用.
如果要创建x 的深层副本(即也要复制子列表),请使用:
import copy
y = copy.deepcopy(x)
Run Code Online (Sandbox Code Playgroud)