a = 1
b = a
a = 2
print(a, b)
print(id(a), id(b))
"""
运行结果
2 1
1445293568 1445293536
""" # 列表直接复赋值给列表不属于拷贝, 只是内存地址的引用
list1 = ["a", "b", "c"]
list2 = list1
list1.append("d")
print(list1, list2)
print(id(list1), id(list2))
"""
运行结果
['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']
1947385383176 1947385383176
""" # 浅拷贝
list1 = ["a", "b", "c"]
list2 = list1.copy()
list1.append("d")
print(list1, list2)
print(id(list1), id(list2))
"""
运行结果:
['a', 'b', 'c', 'd'] ['a', 'b', 'c']
1553315383560 1553315556936
""" # 浅拷贝, 只会拷贝第一层, 第二层的内容不会拷贝
list1 = ["a", "b", "c", [1, 2, 3]]
list2 = list1.copy()
list1[3].append(4)
print(list1, list2)
print(id(list1), id(list2))
"""
运行结果
['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3, 4]]
1386655149640 1386655185672
""" # 深拷贝
import copy
list1 = ["a", "b", "c", [1, 2, 3]]
list2 = copy.deepcopy(list1)
list1[3].append(4)
print(list1, list2)
print(id(list1), id(list2))
"""
运行结果
['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3]]
1452762592904 1452762606664
"""
05-15 01:25