Lab: Type Detective
Lab: Type Detective
Section titled “Lab: Type Detective”ในแล็บนี้คุณจะเป็น “นักสืบชนิดข้อมูล” ที่ต้องตรวจสอบข้อมูลจาก e-commerce และแปลงให้อยู่ในรูปแบบที่ถูกต้องก่อนนำไปวิเคราะห์
-
สร้างข้อมูลจำลอง
สร้าง list ของ dict ที่เก็บข้อมูลคำสั่งซื้อ:
orders = [{"id": "001", "product": "เสื้อยืด", "price": "350", "qty": "2", "discount": "10%"},{"id": "002", "product": "กางเกง", "price": "N/A", "qty": "1", "discount": ""},{"id": "003", "product": "รองเท้า", "price": "1200.50", "qty": "3", "discount": "5%"},{"id": "004", "product": "หมวก", "price": "299", "qty": "ห้า", "discount": "0%"},] -
ตรวจสอบชนิดข้อมูล
เขียน loop ตรวจสอบ type ของทุก value ในแต่ละ order แล้ว print ผลลัพธ์
-
แปลง price เป็น float
เขียนฟังก์ชัน
clean_price(value)ที่:- แปลง string เป็น float ได้ → return float
- แปลงไม่ได้ → return
None
-
แปลง discount เป็นตัวเลข
เขียนฟังก์ชัน
parse_discount(value)ที่:- ลบเครื่องหมาย
%ออก - แปลงเป็น float แล้วหาร 100
- ค่าว่าง → return
0.0
- ลบเครื่องหมาย
-
คำนวณยอดรวม
สร้าง list ใหม่ที่มี
total=price * qty * (1 - discount)สำหรับแต่ละ order ถ้า price หรือ qty แปลงไม่ได้ ให้ total = None
Show Solution
# Step 2: ตรวจสอบชนิดข้อมูลfor order in orders: print(f"Order {order['id']}:") for key, value in order.items(): print(f" {key}: {value!r} → {type(value).__name__}")
# Step 3: clean_pricedef clean_price(value): try: return float(value) except (ValueError, TypeError): return None
# Step 4: parse_discountdef parse_discount(value): if not value or value.strip() == "": return 0.0 try: return float(value.replace("%", "")) / 100 except ValueError: return 0.0
# Step 5: คำนวณยอดรวมdef safe_int(value): try: return int(value) except (ValueError, TypeError): return None
results = []for order in orders: price = clean_price(order["price"]) qty = safe_int(order["qty"]) discount = parse_discount(order["discount"])
if price is not None and qty is not None: total = price * qty * (1 - discount) else: total = None
results.append({ "id": order["id"], "product": order["product"], "total": total })
for r in results: total_str = f"{r['total']:,.2f}" if r['total'] else "N/A" print(f"{r['id']} {r['product']}: {total_str} บาท")