ข้ามไปยังเนื้อหา

โครงสร้างข้อมูล

Python มี container ประเภทใช้งานทั่วไปสี่ชนิดในตัวภาษา ไม่ต้อง import ใด ๆ

ประเภทSyntaxเปลี่ยนแปลงได้มีลำดับซ้ำได้
list[1, 2, 3]ได้ได้ได้
tuple(1, 2, 3)ไม่ได้ได้ได้
dict{"a": 1}ได้ได้ (3.7+)key: ไม่ได้
set{1, 2, 3}ได้ไม่ได้ไม่ได้

แต่ละประเภทมีจุดเด่นต่างกัน: list สำหรับลำดับที่แก้ไขได้, tuple สำหรับข้อมูลคงที่, dict สำหรับการค้นหาด้วย key, และ set สำหรับทดสอบสมาชิกภาพ

  • ใช้ list เมื่อต้องการ append, sort หรือเข้าถึงข้อมูลด้วย index
  • ใช้ tuple เมื่อข้อมูลคงที่และตำแหน่งมีความหมาย (เช่น สี RGB, แถวในฐานข้อมูล)
  • ใช้ dict เมื่อต้องการค้นหาด้วย key อย่างรวดเร็ว หรือจัดกลุ่ม attribute ที่มีชื่อโดยไม่ต้องสร้าง class
  • ใช้ set เมื่อต้องการความเป็นเอกลักษณ์ หรือต้องการ union / intersection / difference
from collections import namedtuple
# --- list ---
nums = [1, 2, 3, 4, 5]
print('list:', nums)
print('sum:', sum(nums))
# --- tuple unpacking ---
coords = (10, 20, 30)
x, y, z = coords
print('tuple unpack:', x, y, z)
# --- dict (insertion order preserved since Python 3.7) ---
scores = {'alice': 95, 'bob': 87, 'carol': 92}
print('dict:', scores)
print('alice score:', scores['alice'])
# --- set (duplicates removed automatically) ---
unique = {3, 1, 4, 1, 5, 9, 2, 6, 5}
print('set:', sorted(unique))
# --- namedtuple: lightweight named record ---
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print('namedtuple:', p.x, p.y)
Collection ประเภทใดที่ไม่อนุญาตให้มีค่าซ้ำ?
ตั้งแต่ Python 3.7 collection ใดที่รักษาลำดับการแทรก?
Collection ใดที่เปลี่ยนแปลงไม่ได้ (immutable)?
ประเภทใดเหมาะสมที่สุดสำหรับการทดสอบสมาชิกภาพของข้อมูลจำนวนมาก?