การจัดการกับข้อมูลประเภทผสมแบบซ้อนกัน
ก่อนหน้านี้เราใช้นิพจน์ in เพื่อตรวจสอบว่ามีข้อมูลอยู่ใน dictionary หรือไม่ เช่น if 'cookies' in recipes_dict แต่ถ้าต้องการค้นหาข้อมูลใน key ของ dictionary ที่เก็บ list ของ dictionary ซ้อนกันอยู่ล่ะ? ในกรณีนี้ เราสามารถใช้ for loop เพื่อวนซ้ำรายการใน list ที่ซ้อนอยู่ได้ นอกจากนี้ยังใช้ list comprehension เพื่อกรองข้อมูลจาก list ของ dictionary แบบซ้อนกันได้อย่างมีประสิทธิภาพ ตัวอย่างเช่น [cookie for cookie in recipes["cookies"] if "chocolate chip" in cookie["name"]] จะคืนค่า list ของคุกกี้ใน recipes ที่มีคำว่า chocolate chip อยู่ใน key name ของคุกกี้นั้น
เราได้โหลด dictionary ชื่อ squirrels_by_park ไว้ให้แล้ว โดยใช้ชื่อสวนสาธารณะเป็น key และเก็บ list ของ dictionary ข้อมูลกระรอกแต่ละตัวเป็น value
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ประเภทข้อมูลใน Python
คำแนะนำการฝึกหัด
- ใช้ for loop วนซ้ำกระรอกที่พบใน key
Tompkins Square Parkของsquirrels_by_park:- พิมพ์ activities ของกระรอกแต่ละตัวอย่างปลอดภัย
- พิมพ์ list ของกระรอกที่มี
primary_fur_colorเป็น'Cinnamon'ในUnion Square Parkโดยใช้ list comprehension
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Use a for loop to iterate over the squirrels in Tompkins Square Park:
for squirrel in ____["____"]:
# Safely print the activities of each squirrel or None
print(____.____("____"))
# Print the list of 'Cinnamon' primary_fur_color squirrels in Union Square Park
print([squirrel for squirrel in ____["____"] if "____" ____ ____["____"]])