热线电话:13121318867

登录
2018-12-19 阅读量: 713
如何理解pyhton的深拷贝?

Python中的赋值语句不复制对象,它们在目标和对象之间创建绑定。对于可变或包含可变项的集合,有时需要一个副本,因此可以更改一个副本而不更改另一个副本。

深拷贝

在深层复制的情况下,对象的副本将复制到其他对象中。这意味着对对象副本所做的任何更改都不会反映在原始对象中。

在python中,这是使用“deepcopy()”函数实现的。

# Python code to demonstrate copy operations

# importing "copy" for copy operations

import copy

# initializing list 1

li1 = [1, 2, [3,5], 4]

# using deepcopy to deep copy

li2 = copy.deepcopy(li1)

# original elements of list

print ("The original elements before deep copying")

for i in range(0,len(li1)):

print (li1[i],end=" ")

print("\r")

# adding and element to new list

li2[2][0] = 7

# Change is reflected in l2

print ("The new list of elements after deep copying ")

for i in range(0,len( li1)):

print (li2[i],end=" ")

print("\r")

# Change is NOT reflected in original list

# as it is a deep copy

print ("The original elements after deep copying")

for i in range(0,len( li1)):

print (li1[i],end=" ")

0.0000
0
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子