# 愚公移山日记·38

# 简单不可变类型都是浅拷贝
# 元组，字符串，数字 都是不可变
import copy

def test_copy():
tiple1 = (1, 2, 3)
print('tuple1 = ', tiple1, id(tiple1))
# 对简单不可变类型进行浅拷贝
# 等价于 tuple2 = tiple1
tuple2 = copy.copy(tiple1)
print('tuple2 = ', tuple2, id(tuple2))

tiple1 = (1, 2, 3)
print('tuple1 = ', tiple1, id(tiple1))
# 对简单不可变类型进行浅拷贝
# 等价于 tuple2 = tiple1
tuple2 = copy.deepcopy(tiple1)
print('tuple2 = ', tuple2, id(tuple2))

# 简单不可变类型 无论深拷贝还是浅拷贝 都无法创建新的内存空间

# 含有嵌套关系的
import copy

def test():
A = [1, 2]
B = [3, 4]
C = [A, B]

print('A = ', A, id(A))
print('B = ', B, id(B))
print('C = ', C, id(C))
print('C[0]', C[0], id(C[0]))
# 复杂可变类型进行浅拷贝
D = copy.copy(C)
print('D = ', D, id(D))
print('D[0] = ', D[0], id(D[0]))

# 修改A的
A[0] = 10
print('A = ', A, id(A))
print('D[0] = ', D[0], id(D[0]))

def test2():
A = [1, 2]
B = [3, 4]
# [[1, 2],[3, 4]]
C = [A, B]

print('A = ', A, id(A))
# print('B = ', B, id(B))
print('C = ', C, id(C))
# print('C[0]', C[0], id(C[0]))

D = copy.deepcopy(C)
print('D = ', D, id(D))
print('D[0]= ', id(D[0]), 'c[0] = ', id(C[0]), 'A[0] = ', id(A[0]))

# 修改A的
A[0] = 10
print('A = ', A, id(A))
print('D[0] = ', D[0], id(D[0]))

test2()

python中的切片拷贝，字典拷贝

def test():
# 简单可变 深拷贝
list1 = [1, 2, 3, 4, 56]
print('list1 = ', list1, id(list1))
# 切片拷贝
list2 = list1[:]
print('list = ', list, id(list))

def test2():
A = [1, 2]
B = [3, 4]
C = (A, B)
print('C = ', C, id(C))
D = C[:]
print('D = ', D, id(D))
D[0][0] = 4

# 字典拷贝,浅拷贝
dict1 = {'age': [1, 2]}
print('dict1 = ', dict1, id(dict1))
dict2 = dict1.copy()
print('dict2 = ', dict2, id(dict2))
print('--'*10)
dict1['age'][0] = 10
print('dict1 = ', dict1, id(dict1))
print('dict2 = ', dict2, id(dict2))

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

Python_G－Dragon

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

04-30 49
04-20 45

03-27 69
03-25 40
03-29 70
04-02 57
04-28 61
04-26 42
03-20 63
03-30 65
12-21
04-08 46
04-11 60
04-13 46
04-03 53
04-14 53
03-21 70
03-22 76
08-20