python-多重list的拷贝

单重list的拷贝

1
2
3
4
5
6
7
8
9
10
a = [1, 2, 3]
b = a
c = a[:]

a.append(4)
a[0] = 5

print("原数组:", a)
print("引用赋值:", b)
print("拷贝:", c)
原数组: [5, 2, 3, 4]
引用赋值: [5, 2, 3, 4]
拷贝: [1, 2, 3]

多重list的拷贝

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import copy

a = [[1, 2, 3], [4, 5, 6]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)

a.append(47)
a[0][0] = 10

print("原数组:", a)
print("引用赋值:", b)
print("浅拷贝:", c)
print("深拷贝:", d)
原数组: [[10, 2, 3], [4, 5, 6], 47]
引用赋值: [[10, 2, 3], [4, 5, 6], 47]
浅拷贝: [[10, 2, 3], [4, 5, 6]]
深拷贝: [[1, 2, 3], [4, 5, 6]]