ตัวอย่างโค้ดที่มีปัญหา
โค้ด: เลือกทั้งหมด
# importing copy module
import copy
# initializing list 1
li1 = [1, 2, [3,5], 4]
# 1st way to copy a list (shallow copy)
# li2(memory address) = li1(memory address)
li2 = copy.copy(li1)
# 2nd way to copy a list (shallow copy)
# li3(memory address) = li1(memory address)
li3 = li1
# show them all in the terminal
print(f'list1 = {li1}')
print(f'list2 = {li2}')
print(f'list3 = {li3}')
li1[2][0] = 7
print()
print('list1[2][0] = 7')
print(f'list1 = {li1}')
print(f'list2 = {li2}')
print(f'list3 = {li3}')
วิธีแก้ปัหา
ถ้าเราต้องการจะ copy list แต่ไม่อยากให้ ตำแหน่ง RAM มันตรงกัน ปัญหานี้จะถูกแก้ด้วยฟังก์ชั่น deepcopy
ยกตัวอย่างโค้ดที่ใช้ฟังก์ชั่น deepcopy
โค้ด: เลือกทั้งหมด
# importing copy module
import copy
# initializing list 1
li1 = [1, 2, [3,5], 4]
# the way to copy a list (deep copy)
# li2(memory address) != li1(memory address)
li2 = copy.deepcopy(li1)
# show them all in the terminal
print(f'list1 = {li1}')
print(f'list2 = {li2}')
li1[2][0] = 7
print()
print('list1[2][0] = 7')
print(f'list1 = {li1}')
print(f'list2 = {li2}')
สรุป
จากการตั้งสมมติฐานเหตุผลที่ทำให้เกิดปัญหาเหมือนในตัวอย่างแรกว่า มันไม่ได้ copy ค่า มา แต่มัน copy ตำแหน่งของ RAM มาแทน
หลังจากที่ไปหาข้อมูลมาเพิ่มเติม ก็ปรากฎว่า สมมติฐานเราเป็นจริง เย่!2 (มีลิงก์แนบไว้ในอ้างอิง)
แล้วผลจากตัวอย่างที่2 ทำให้เรารู้ว่ามันแก้ปัญหา shallow copy ได้โดยใช้ฟังก์ชั่น deepcopy
อ้างอิง
quickserv.co.th/knowledge-base/solutions/RAM
geeksforgeeks.org
docs.python.org/3/library/copy
youtu.be