a=1 b=a a=2
a = 1 b = a print(a, b) a += 2 print(a, b) print("a id:", id(a)) print("b id:", id(b)) # 输出结果 1 1 2 1 a id: 4564097808 b id: 4564097776
a = [1, 2, 3] b = a print(a, b) a[1] = 22 print(a, b) print("a id:", id(a)) print("b id:", id(b)) # 输出结果 [1, 2, 3] [1, 2, 3] [1, 22, 3] [1, 22, 3] a id: 4567683136 b id: 4567683136
Python 提供了 copy 模块,包含了浅拷贝、深拷贝函数
from copy import copy, deepcopy # 浅拷贝 copy(x) # 深拷贝 deepcopy(x)
一句话概括:浅拷贝会创建一个新对象,该新对象存储原始元素的引用
import copy old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] new_list = copy.copy(old_list) print("Old list:", old_list) print("New list:", new_list) # 输出结果 Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
import copy old_list = [[1, 2], [3, 4]] new_list = copy.copy(old_list) old_list.append([5, 6]) print("Old list:", old_list, "id is :", id(old_list)) print("New list:", new_list, "id is :", id(new_list)) # 输出结果 Old list: [[1, 2], [3, 4], [5, 6]] id is : 4366240704 New list: [[1, 2], [3, 4]] id is : 4366246720
可以看到内存地址是不同的,所以给 old_list 新增一个元素并不会同步让 new_list 也新增
上面的栗子是直接添加元素,来看看修改元素会怎么样
# 不可变元素 import copy old_list = [1, 2, "string", (1, 2,)] new_list = copy.copy(old_list) old_list[1] += 22 old_list[2] += "s" old_list[3] += (3,) print("Old list:", old_list) print("New list:", new_list) # 输出结果 Old list: [1, 24, 'strings', (1, 2, 3)] New list: [1, 2, 'string', (1, 2)]
修改 old_list 的三种不可变对象元素,均不会同步给 new_list
# 可变元素 import copy old_list = [[1, 2], [3, 4]] new_list = copy.copy(old_list) old_list[0][0] += 99 old_list[1][0] += 97 print("Old list:", old_list, "old list id:", id(old_list), " old list[0] id:", id(old_list[0])) print("new list:", new_list, "new list id:", id(new_list), " new list[0] id:", id(new_list[0])) # 输出结果 Old list: [[100, 2], [100, 4]] old list id: 4430308096 old list[0] id: 4430302400 new list: [[100, 2], [100, 4]] new list id: 4430308416 new list[0] id: 4430302400
从输出结果看到
# 深拷贝 old_list = [[1, 2], [3, 4]] new_list = copy.deepcopy(old_list) old_list[0][0] += 99 old_list[1][0] += 97 print("Old list:", old_list, "old list id:", id(old_list), " old list[0] id:", id(old_list[0])) print("new list:", new_list, "new list id:", id(new_list), " new list[0] id:", id(new_list[0])) # 输出结果 Old list: [[100, 2], [100, 4]] old list id: 4430308480 old list[0] id: 4430211392 new list: [[1, 2], [3, 4]] new list id: 4430308096 new list[0] id: 4430308864
从输出结果看到
假设是一个三维列表呢
# 深拷贝-三维数组 old_list = [[1, [10, 9]], [3, 4]] new_list = copy.deepcopy(old_list) old_list[0][1][0] += 90 print("Old list:", old_list) print("New list:", new_list) # 输出结果 Old list: [[1, [100, 9]], [3, 4]] New list: [[1, [10, 9]], [3, 4]]
两个变量依旧是独立的
https://www.cnblogs.com/poloyy/p/15086511.html