Python มีชนิดข้อมูลที่ไม่เปลี่ยนแปลงได้ (immutable) ที่เรียกว่า tuples ในบทความนี้ เราจะเรียนรู้เกี่ยวกับการแพ็ค (packing) และการแตก (unpacking) tuple type ใน Python 3.x หรือเวอร์ชันก่อนหน้า
การแพ็คและแตกทูเพิล (Packing and Unpacking a Tuple)
Python มีเครื่องมือการกำหนดค่าทูเพิลที่ทรงพลังมากที่แมปอาร์กิวเมนต์ฝั่งขวาเข้าไปในอาร์กิวเมนต์ฝั่งซ้าย การแมปแบบนี้ร่วมกันเรียกว่า unpacking ของทูเพิลค่าเข้าไปในตัวแปรปกติ ในขณะที่ packing เราใส่ค่าเข้าไปในทูเพิลปกติโดยวิธีการกำหนดค่าปกติ
ตอนนี้มาดูการนำไปใช้งาน
ตัวอย่าง
# Packing tuple variables under one variable name
tup = ("Tutorialspoint", "Python", "Unpacking a tuple")
# Packing tuple variables into a group of arguments
(website, language, topic) = tup
# print college name
print(website, "\t", language, " ", topic)
ผลลัพธ์
Tutorialspoint Python Unpacking a tuple
ระหว่างการ unpack tuple จำนวนตัวแปรฝั่งซ้ายควรเทียบเท่ากับจำนวนค่าทั้งหมดในทูเพิล tup ที่กำหนด
Python ให้ syntax สำหรับส่งอาร์กิวเมนต์ออปชัน (*arguments) สำหรับการ unpack tuple ความยาวกำหนดเอง (arbitrary length) ค่าทั้งหมดจะถูกกำหนดให้ทุกตัวแปรตามลำดับการระบุ และค่าที่เหลือทั้งหมดจะถูกกำหนดให้ *arguments มาดูโค้ดต่อไปนี้
ตัวอย่าง
# Packing tuple variables under one variable name
tup = ("Tutorialspoint", "Python", "3.x.", ":Data Structure", "Unpacking a tuple")
# Packing tuple variables into a group of arguments
(website, *language, topic) = tup
# print college name
print(website, "\t", *language, " ", topic)
ผลลัพธ์
Tutorialspoint Python 3.x. :Data Structure Unpacking a tuple
ใน Python tuples สามารถแตกได้โดยใช้ฟังก์ชัน ในฟังก์ชัน tuple ถูกส่งผ่านและในฟังก์ชัน ค่าถูกแตกเข้าไปในตัวแปรปกติ โค้ดต่อไปนี้อธิบายวิธีจัดการกับจำนวนอาร์กิวเมนต์กำหนดเอง
"*_" ใช้ระบุจำนวนอาร์กิวเมนต์กำหนดเองในทูเพิล
ตัวอย่าง
# Packing tuple variables under one variable name
tup = ("Tutorialspoint", "Python", "3.x.", "Data Structure:", "Unpacking a tuple")
# UnPacking tuple variables into a group of arguments and skipping unwanted arguments
(website, *_, typ, topic) = tup
# print college name
print(website, "\t", typ, " ", topic)
ผลลัพธ์
Tutorialspoint Data Structure: Unpacking a tuple
ในกรณีที่เราต้องการข้ามเพียงอาร์กิวเมนต์เดียว เราสามารถแทนที่ "*_" ด้วย "_"
สรุป
ในบทความนี้ เราได้เรียนรู้วิธีที่เราสามารถแพ็คและแตกทูเพิลได้ในหลากหลายวิธี