Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เปรียบเทียบ List vs Tuple vs Dictionary ใน Python

List และ Tuple เป็น Sequences (ลำดับข้อมูล) Dictionary เป็น Hash Table ของคู่ key-value List และ Tuple เป็น Ordered collection (คอลเลกชันที่มีลำดับ) Dictionary เป็น Unordered collection

List และ Dictionary เป็น Mutable (เปลี่ยนแปลงได้) สามารถเพิ่มหรือลบรายการได้ Tuple เป็น Immutable object (ไม่เปลี่ยนแปลงได้) ไม่สามารถเพิ่มหรือลบรายการบน Tuple ได้

ทุกประเภทเป็นคอลเลกชันของรายการที่คั่นด้วยคอมมา List ใช้วงเล็บเหลี่ยม [] Tuple ใช้วงเล็บมุม () Dictionary ใช้วงเล็บปีกกา {}

>> L1 = [12, "Ravi", "B.Com FY", 78.50]  # list
>>> T1 = (12, "Ravi", "B.Com FY", 78.50) # tuple
>>> D1 = {"Rollno": 12, "class": "B.com FY", "precentage": 78.50} # dictionary

List และ Tuple มีดัชนี ใช้ Slice operator เข้าถึงรายการได้

>> print(L1[2])
B.Com FY
>>> print(T1[2])
B.Com FY

Dictionary ไม่มีดัชนี ใช้ key เข้าถึงค่า

>> print(D1['class'])
B.com FY
>>> print(D1.get('class'))
B.com FY