06 List, Tuple, Dictionary และ Set
Collection ใน Python
Collection คือโครงสร้างข้อมูลที่ใช้เก็บหลายค่าในตัวแปรเดียว
List
List ใช้เก็บข้อมูลแบบเรียงลำดับและแก้ไขได้
fruits = ["apple", "banana", "orange"]
print(fruits[0])
fruits.append("mango")
fruits.remove("banana")
print(fruits)
Slice
numbers = [10, 20, 30, 40, 50]
print(numbers[0:3])
print(numbers[2:])
print(numbers[-1])
Tuple
Tuple คล้าย list แต่แก้ไขค่าไม่ได้ เหมาะกับข้อมูลที่ควรคงที่
point = (10, 20)
print(point[0])
Dictionary
Dictionary เก็บข้อมูลแบบ key-value
student = {
"name": "Ann",
"score": 85,
"is_passed": True,
}
print(student["name"])
student["score"] = 90
อ่าน dictionary ด้วย loop:
for key, value in student.items():
print(key, value)
List of Dictionaries
รูปแบบนี้เจอบ่อยมากในงานข้อมูล
orders = [
{"id": 1, "amount": 1200},
{"id": 2, "amount": 850},
{"id": 3, "amount": 430},
]
total = 0
for order in orders:
total += order["amount"]
print(total)
Set
Set ใช้เก็บค่าที่ไม่ซ้ำ
tags = {"python", "sql", "python"}
print(tags)
เลือกใช้อะไรดี
- ใช้ list เมื่อต้องเก็บข้อมูลเรียงลำดับ
- ใช้ tuple เมื่อข้อมูลไม่ควรถูกแก้
- ใช้ dictionary เมื่อข้อมูลมีชื่อ field
- ใช้ set เมื่อต้องการกำจัดค่าซ้ำ
แบบฝึกหัด
- สร้าง list ของสินค้า 3 รายการ แต่ละรายการเป็น dictionary
- แต่ละสินค้ามี
name,price,quantity - วน loop เพื่อคำนวณยอดขายรวม
- สร้าง set ของชื่อสินค้าเพื่อดูชื่อที่ไม่ซ้ำ