Skip to content

Lists & Dicts

เมื่อข้อมูลมีหลายชิ้น เราต้องมีโครงสร้างที่จัดเก็บได้อย่างเป็นระบบ Python มี 2 โครงสร้างหลักที่ใช้บ่อยที่สุดในงาน Data

Lists — ลำดับข้อมูล

Section titled “Lists — ลำดับข้อมูล”
# สร้าง list
prices = [100, 250, 75, 430, 199]
names = ["Alice", "Bob", "Charlie"]
# เข้าถึงด้วย index (เริ่มจาก 0)
print(prices[0]) # 100
print(prices[-1]) # 199 (ตัวสุดท้าย)
# slice — ตัดช่วง
print(prices[1:3]) # [250, 75]
# เพิ่ม / ลบ
prices.append(320)
prices.remove(75)
# วนลูป
for p in prices:
print(f"ราคา {p} บาท")
# ฟังก์ชันที่ใช้บ่อย
print(len(prices)) # จำนวนสมาชิก
print(sum(prices)) # ผลรวม
print(max(prices)) # ค่ามากสุด
print(min(prices)) # ค่าน้อยสุด
# สร้าง dict
product = {
"name": "เสื้อยืด",
"price": 350,
"in_stock": True,
"sizes": ["S", "M", "L"]
}
# เข้าถึงค่า
print(product["name"]) # เสื้อยืด
print(product.get("color", "N/A")) # N/A (default ถ้าไม่มี key)
# เพิ่ม / แก้ไข
product["color"] = "แดง"
product["price"] = 299
# วนลูป
for key, value in product.items():
print(f"{key}: {value}")
# แบบปกติ
doubled = []
for p in prices:
doubled.append(p * 2)
# แบบ comprehension — สั้นกว่า
doubled = [p * 2 for p in prices]
# พร้อมเงื่อนไข
expensive = [p for p in prices if p > 200]
# Dict comprehension
price_map = {f"item_{i}": p for i, p in enumerate(prices)}