Python中可变对象的深拷贝与浅拷贝

1. python中赋值

a = [3,6,9,4,7]
b = a

此时b和a指向同一内存地址,如果a中元素发生变化,b中也会发生变化。如

a[0]=4
print(b)

output:[4, 6, 9, 4, 7]

2. 浅copy

import copy
a = [3,6,9,4,[7]]
b = copy.copy(a)
a[0] = 4
print(b)

output:[3, 6, 9, 4, [7]]

但是

a[-1].append(9)
print(b)

output:[3, 6, 9, 4, [7, 9]]

并不能完全将二者隔离。

3. 深拷贝

import copy
a = [3,6,9,4,[7]]
b = copy.deepcopy(a)
a[0] = 4
print(b)
a[-1].append(9)
print(b)

output1:[3, 6, 9, 4, [7]]
output2:[3, 6, 9, 4, [7]]

你可能感兴趣的:(Python中可变对象的深拷贝与浅拷贝)