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

ความแตกต่างระหว่าง Python Tuple และ Dictionary

โครงสร้างข้อมูลต่างกันมาก Elements ใน tuple มีคุณสมบัติ:

  • รักษาลำดับ (Order maintained)
  • Immutable
  • เก็บ type ใดก็ได้ และผสม type ได้
  • เข้าถึงด้วย numeric index (zero-based)

Python dictionary เป็น hash table implementation Elements มีคุณสมบัติ:

  • ไม่รับประกันลำดับ (Ordering not guaranteed)
  • ทุก entry มี key และ value
  • เข้าถึงด้วย key values
  • Entries เปลี่ยนแปลงได้
  • Key types ใดก็ได้ที่ hashable (ไม่ใช่ dict) ผสมได้ Value types ใดก็ได้ (รวม dict) ผสมได้

ทั้งคู่สร้างได้ด้วย comprehensions ตัวอย่าง:

Tuple: (1, 'a', (3, 6, 8), 'string')
Dictionary: {'foo': [1, 2, 3], 'bar': 'baz'}