วิธีแก้ปัญหา shallow copy ใน Python list(Python3)

แนะนำ สอบถาม ภาษา C สำหรับผู้เริ่มต้น ภาษา Java ภาษา Python

Moderator: mindphp, ผู้ดูแลกระดาน

annie2301
PHP Super Member
PHP Super Member
โพสต์: 289
ลงทะเบียนเมื่อ: 01/12/2021 9:44 am

วิธีแก้ปัญหา shallow copy ใน Python list(Python3)

โพสต์ที่ยังไม่ได้อ่าน โดย annie2301 »

ปัญหาที่เรียกว่า shallow copy คือ การที่กำหนดค่าโดยเอาตำแหน่งของ RAM ของอีกตัวแปรหนึ่งมากำหนดค่า(ตั้งสมมติฐาน) เพื่อให้เข้าใจตรงกัน จะยกตัวอย่างโค้ดที่มีปัญหามา 1 ไฟล์

ตัวอย่างโค้ดที่มีปัญหา

โค้ด: เลือกทั้งหมด

# 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 และ กำหนดค่าด้วย =
ตัวอย่างผลลัพธ์ที่ใช้ฟังก์ชั่น copy และ กำหนดค่าด้วย =
shallow_copy.PNG (3.88 KiB) Viewed 742 times
จากรูปผลลัพธ์จะเห็นว่า เมื่อเปลี่ยนค่า list1 ที่ rowที่ 2 , cloumnที่ 0 เป็น 7 แล้ว list2 และ list3 ก็เปลี่ยนไปตาม list1 ด้วย



วิธีแก้ปัหา

ถ้าเราต้องการจะ 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}')
ตัวอย่างผลลัพธ์ที่ใช้ฟังก์ชั่น deepcopy
ตัวอย่างผลลัพธ์ที่ใช้ฟังก์ชั่น deepcopy
deep_copy.PNG (6.18 KiB) Viewed 742 times
จากรูปตัวอย่างการใช้ฟังก์ชั่น deepcopy จะเห็นว่ามันแก้ปัญหาได้แล้ว เย่!



สรุป
จากการตั้งสมมติฐานเหตุผลที่ทำให้เกิดปัญหาเหมือนในตัวอย่างแรกว่า มันไม่ได้ 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
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 35