Python-學習筆記-賦值和淺複製與深複製(copy&deepcopy)
# -*- coding:utf-8 -*-
####################################################################################
#
# python序列分爲 容器序列 和 扁平序列
#
#
# 另一種維度上分爲 可變序列 和 不變序列
#
# 不變序列有3:tuple、set、bytes
#
# 可變序列有: list、array.array、array.bytearray、memoryview
#
####################################################################################
# 簡介:python序列複製分爲 1.不可變序列賦值(普通) 2.可變元素單維度複製(淺複製) 3.可變元素多維度複製(深複製)
# 淺複製和深複製只適合於可變序列 也就是內存值會發生變化的序列
# 1. 普通序列賦值(只是掛載引用)
# 1.1 不變序列
print('\nNormal Voluation(create new memery):')
x = 1
y = x
x = 2
print(x) # 2 指向新內存地址
print(y) # 1 指向舊內存地址
# 1.2 可變序列(產生問題 - 需要使用淺複製)
lst01 = [1, 2, 3] # 原始內存
lst02 = lst01 # 賦值引用關係
lst01[2] = 4 # 原始可變序列變化
print('\nNormal Voluation(old memery):')
print(lst01) # 指向 原始內存
print(lst02) # 指向 原始內存 - 發現lst02[2]也變成了4, 因爲lst02引用lst01
# 2.淺複製 obj.copy()
# 2.1 一維度淺複製(元素項爲不可變序列)
lst01 = [1, 2, 3]
lst02 = lst01.copy() # 新創建對象 新內存
lst01[2] = 4
print('\nCopy - One Dimension:')
print(lst01) # [1,2,4]
print(lst02) # [1,2,3]
# 2.2 多維度淺複製(淺複製問題 - 需要使用深複製)
# 多維內部 如果有可變序列子項,外部是淺複製,內部子項依舊是引用
lst01 = [1, 2, [3, 4]]
lst02 = lst01.copy() # 新創建對象 新內存
lst01[2][1] = 3 # [3,4]爲一維列表中的一個元素 複製時候採取引用複製的方式
print('\nCopy - Multi Dimensions:')
print(lst01) # [1, 2, [3, 3]]
print(lst02) # [1, 2, [3, 3]]
# 3. 深複製 copy.deepcopy(obj)
# 3.1 N維度序列均重新生成 無任何舊源引用
import copy
lst01 = [1, 2, [3, 4]]
lst02 = copy.deepcopy(lst01) # 新創建對象 新內存,任何子維度的元素項全部依次使用copy()創建新對象 沒有任何源序列引用關係
lst01[2][1] = 3
print('\nDeepcopy:')
print(lst01) # [1, 2, [3, 3]]
print(lst02) # [1, 2, [3, 4]]