python深浅拷贝
code
import copy age = 19 print(f'first:{id(age)}') age = 20 print(f'second:{id(age)}') l1 = ['a', 'b', 'c', ['d', 'e', 'f']] l2 = l1 print("*"*25,"赋值","*"*25) l1.append('g') print("l1:",l1) print("l2:",l2) l1 = ['a', 'b', 'c', ['d', 'e', 'f']] l2 = copy.copy(l1) print("*"*25,"浅拷贝-修改不可变元素","*"*25) l1.append('g') print("l1:",l1) print("l2:",l2) print("*"*25,"浅拷贝-修改可变元素","*"*25) l1[3].append('g') print("l1:",l1) print("l2:",l2) l1 = ['a', 'b', 'c', ['d', 'e', 'f']] l2 = copy.deepcopy(l1) print("*"*25,"深拷贝-修改不可变元素","*"*25) l1.append('g') print("l1:",l1) print("l2:",l2) print("*"*25,"深拷贝-修改可变元素","*"*25) l1[3].append('g') print("l1:",l1) print("l2:",l2)
Outputs
macname@MacdeMacBook-Pro py % python3 cccccc.py first:4525530480 second:4525530512 ************************* 赋值 ************************* l1: ['a', 'b', 'c', ['d', 'e', 'f'], 'g'] l2: ['a', 'b', 'c', ['d', 'e', 'f'], 'g'] ************************* 浅拷贝-修改不可变元素 ************************* l1: ['a', 'b', 'c', ['d', 'e', 'f'], 'g'] l2: ['a', 'b', 'c', ['d', 'e', 'f']] ************************* 浅拷贝-修改可变元素 ************************* l1: ['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g'] l2: ['a', 'b', 'c', ['d', 'e', 'f', 'g']] ************************* 深拷贝-修改不可变元素 ************************* l1: ['a', 'b', 'c', ['d', 'e', 'f'], 'g'] l2: ['a', 'b', 'c', ['d', 'e', 'f']] ************************* 深拷贝-修改可变元素 ************************* l1: ['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g'] l2: ['a', 'b', 'c', ['d', 'e', 'f']] macname@MacdeMacBook-Pro py %