Lists & Dicts
Lists & Dicts
Section titled “Lists & Dicts”เมื่อข้อมูลมีหลายชิ้น เราต้องมีโครงสร้างที่จัดเก็บได้อย่างเป็นระบบ Python มี 2 โครงสร้างหลักที่ใช้บ่อยที่สุดในงาน Data
Lists — ลำดับข้อมูล
Section titled “Lists — ลำดับข้อมูล”# สร้าง listprices = [100, 250, 75, 430, 199]names = ["Alice", "Bob", "Charlie"]
# เข้าถึงด้วย index (เริ่มจาก 0)print(prices[0]) # 100print(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)) # ค่าน้อยสุดDictionaries — คู่ key-value
Section titled “Dictionaries — คู่ key-value”# สร้าง dictproduct = { "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}")List Comprehension
Section titled “List Comprehension”# แบบปกติ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 comprehensionprice_map = {f"item_{i}": p for i, p in enumerate(prices)}- List เทียบได้กับ column ของข้อมูล เช่น
A1:A10 - Dict เทียบได้กับ row ที่มี header —
VLOOKUPทำหน้าที่คล้าย key lookup - ไม่มี comprehension — ใช้
ARRAYFORMULAแทน
-- List = ผลลัพธ์จาก SELECT columnSELECT price FROM products;-- Dict = แต่ละ row ใน tableSELECT * FROM products WHERE id = 1;-- Comprehension = SELECT with WHERESELECT price * 2 FROM products WHERE price > 200;// Array (คล้าย List แต่ขนาดคงที่)int prices[] = {100, 250, 75, 430, 199};// C ไม่มี dict ดั้งเดิม ต้องใช้ structstruct Product { char name[50]; int price;};