Programming LanguagePython

การจัดการชุดข้อมูล tuple() และ list()ในภาษา Python

ชุดข้อมูลแบบ tuple() เป็นชุดข้อมูลที่มีโครงสร้างใกล้เคียงกับ list() สามารถเก็บข้อมูลภายในหลายจำนวนในตัวแปรชุดเดียวกัน โดยมีอ้างถึงข้อมูลผ่านการเรียก Index ของชุดข้อมูลภายใน

ตัวอย่างการประกาศตัวแปร แบบ tuple()

Screen Shot 2558-10-10 at 4.32.15 PM

รูปแบบการ ใช้งาน tuple()

avengerTeam =("iron man", "captain america","hulk","black widow")
print (avengerTeam, end="")

ทำการ Run กด F5 ดู

Screen Shot 2558-10-10 at 4.33.35 PM

ตัวอย่างการเรียก Print ค่าใน tuple()

หากว่าเราต้องการเรียกใช้ข้อมูลภายในให้ปรากฏขึ้นมาแค่ตัวเดียวก็ให้ระบุค่า index ลงไปใน [n] ตั้งแต่จำนวน 0,1,2..n เป็นต้น

avengerTeam =("iron man", "captain america","hulk","black widow")
print ("ตัวละครตัวที่ 3 ของทีมคือ:", avengerTeam[2])

Screen Shot 2558-10-10 at 4.37.09 PM

ตัวอย่างเมื่อ run คำสั่งภาษา Python

ความแตกต่างระหว่าง tuple() และ list()

tuple() จะเป็นชุดข้อมูลที่เก็บตัวแปรภายในที่เป็นค่าคงที่ ที่ไม่มีการเปลี่ยนแปลงภายหลัง และเป็นข้อมูลที่ไม่สามารถเพิ่มหรือลบได้หลังจากเพิ่มเข้าไป เพื่อช่วยในการเข้าถึงข้อมูลได้รวดเร็วกว่า การใช้ tuple() จะต้องรู้ตำแหน่ง index ที่แน่นอนก่อนการประกาศ

ข้อดีของภาษา Python คือหากต้องการเปลี่ยนแปลงรูปแบบของตัวแปรแบบ tuple() ไปเป็น list() สามารถใช้คำสั่งแปลงค่าได้ดังนี้

ตัวอย่างในการแปลง tuple() เป็น list() เพื่อจะได้แก้ไข และเพิ่มเติมข้อมูล สำหรับเปลี่ยนแปลงได้คือคำสั่ง

avengerTeam =("iron man", "captain america","hulk","black widow")
avengerList = list(avengerTeam)
print (avengerList,end="")

ทำการ run โปรแกรมของเรา

Screen Shot 2558-10-10 at 4.39.33 PM

ตัวอย่างการแปลงข้อมูลจาก tuple() เป็น list()

ซึ่งเมื่อข้อมูลเป็น list() แล้วเราสามารถใชคำสั่ง list.append() เพิ่มข้อมูลเข้าไปในชุดข้อมูลได้ ดังตัวอย่างเพิ่ม “thor” เข้าไป

avengerTeam =("iron man", "captain america","hulk","black widow")
avengerList = list(avengerTeam)
avengerList.append("thor")
print ("Avenger Member:", avengerList)

ลองรันคำสั่งดูสักหน่อย

Screen Shot 2558-10-10 at 4.42.37 PM

ตัวอย่างการ run ข้อมูลของ list() ที่แปลงจาก tuple() และมีการเพิ่มสมาชิกข้อมูลเข้ามา

Asst. Prof. Banyapon Poolsawas

อาจารย์ประจำสาขาวิชาการออกแบบเชิงโต้ตอบ และการพัฒนาเกม วิทยาลัยครีเอทีฟดีไซน์ & เอ็นเตอร์เทนเมนต์เทคโนโลยี มหาวิทยาลัยธุรกิจบัณฑิตย์ ผู้ก่อตั้ง บริษัท Daydev Co., Ltd, (เดย์เดฟ จำกัด)

Related Articles

Back to top button
Game & Mobile Development AR VR XR
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Adblock Detected

เราตรวจพบว่าคุณใช้ Adblock บนบราวเซอร์ของคุณ,กรุณาปิดระบบ Adblock ก่อนเข้าอ่าน Content ของเรานะครับ, ถือว่าช่วยเหลือกัน