python引用,浅拷贝,深拷贝

1.引用
传递的是引用,原始列表改变,被赋值列表会同样改变,因为他们指向的是同一个地址。

alist = [1,2,3,["a","b"]]
blist = alist
print(alist)
print(blist)
alist.append(5)
print(alist)
print(blist)
alist[3].append(5)
print(alist)
print(blist)

运行结果:

2.浅拷贝
copy浅拷贝,没有拷贝子对象,子对象改变时,会造成赋值的子对象也改变。

import copy
alist = [1,2,3,["a","b"]]
blist = copy.copy(alist)
print(alist)
print(blist)
alist.append(5)
print(alist)
print(blist)
alist[3].append(5)
print(alist)
print(blist)

运行结果:

3.深拷贝
copy深拷贝,会拷贝子对象,原始子对象改变时,不会造成深拷贝的任何子元素改变。

import copy
alist = [1,2,3,["a","b"]]
blist = copy.deepcopy(alist)
print(alist)
print(blist)
alist.append(5)
print(alist)
print(blist)
alist[3].append(5)
print(alist)
print(blist)

运行结果:

posted on 2017-09-18 20:38  迪米特  阅读(154)  评论(0编辑  收藏  举报

导航