python-拷贝

时间:2023-12-17 15:31:26

1.普通的赋值操作

def print_id(array):
ids = []
for ar in array:
ids.append(id(ar))
print (array, ids) a = [1, 'abc', [1, 2, 3]]
b = a
b[0] = 'a'
b[1] = 0
b[2] = [1, 3]
print_id(a)
print_id(b)

output:

(['a', 0, [1, 3]], [4399687320, 140283452869952, 4400308664])
(['a', 0, [1, 3]], [4399687320, 140283452869952, 4400308664])

b = a操作将a对象的地址赋值给b,两个对象的地址相同

2.浅拷贝 copy.copy()

a = [1, 'abc', [1, 2, 3]]
copy_a = copy.copy(a)
copy_a[0] = 'a'
copy_a[1] = 0
copy_a[2] = [1, 3]
print_id(a)
print_id(copy_a)

output:

[1, 'abc', [1, 2, 3]]
['a', 0, [1, 3]]

copy_a = copy.copy(a) 仅仅是把int,float,str类型的数据进行拷贝,重新开辟地址,对于内层的list,dict直接把原有的地址给新的对象