下面展示代码
import copy
浅拷贝:copy.copy
深拷贝:copy.deepcopy
import copy
myList = [0,1,2,["a","b","c"]] # 原列表 original
myListE = myList # 使用等号赋值 assignment using equal sign
myListS = copy.copy(myList) # 浅拷贝 shallow copy
myListD = copy.deepcopy(myList)# 深拷贝 deep copy
print("\n myList:",myList)
print("myListE:",myListE)
print("myListS:",myListS)
print("myListD:",myListD)
print("\n\n\n修改基本类型的元素后:")
myList[0] = 9
print(" myList:",myList)
print("myListE:",myListE)
print("myListS:",myListS)
print("myListD:",myListD)
print("\n\n\n修改引用类型的元素后:")
myList[3][2] = "林麻子..."
print(" myList:",myList)
print("myListE:",myListE)
print("myListS:",myListS)
print("myListD:",myListD)
输出结果:
myList: [0, 1, 2, ['a', 'b', 'c']]
myListE: [0, 1, 2, ['a', 'b', 'c']]
myListS: [0, 1, 2, ['a', 'b', 'c']]
myListD: [0, 1, 2, ['a', 'b', 'c']]
修改基本类型的元素后:
myList: [9, 1, 2, ['a', 'b', 'c']]
myListE: [9, 1, 2, ['a', 'b', 'c']]
myListS: [0, 1, 2, ['a', 'b', 'c']]
myListD: [0, 1, 2, ['a', 'b', 'c']]
修改引用类型的元素后:
myList: [9, 1, 2, ['a', 'b', '林麻子...']]
myListE: [9, 1, 2, ['a', 'b', '林麻子...']]
myListS: [0, 1, 2, ['a', 'b', '林麻子...']]
myListD: [0, 1, 2, ['a', 'b', 'c']]
------------------
(program exited with code: 0)
请按任意键继续. . .