เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การใช้งาน dataclasses

มาใช้งาน dataclass WeightEntry ที่สร้างไว้ในแบบฝึกหัดก่อนหน้ากัน เราจะสร้าง instance ของ WeightEntry สำหรับแต่ละรายการใน weight_log จากนั้นใช้ property mass_to_flipper_length_ratio ที่เพิ่มไว้เพื่อคำนวณค่า ด้านล่างนี้คือ dataclass WeightEntry ของเราเพื่อเป็นการทบทวน

@dataclass
class WeightEntry:
    # Define the fields on the class
    species: str
    flipper_length: int
    body_mass: int
    sex: str

    @property
    def mass_to_flipper_length_ratio(self):
        return self.body_mass / self.flipper_length

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

ประเภทข้อมูลใน Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้างลิสต์ว่างชื่อ labeled_entries
  • วนซ้ำผ่านรายการใน weight_log โดยใช้การขยาย tuple เพื่อแยกค่า species, flipper_length, body_mass, sex
    • เพิ่ม instance ใหม่ของ dataclass WeightEntry สำหรับแต่ละรายการลงใน labeled_entries
  • แสดง 5 ค่าแรกของ mass_to_flipper_length_ratio โดยใช้ list comprehension

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Create the empty list: labeled_entries
labeled_entries = []

# Iterate over the weight_log entries
for species, flipper_length, body_mass, ____ in weight_log:
    # Append a new WeightEntry instance to labeled_entries
    ____.____(____(species, flipper_length, body_mass, ____))
    
# Print a list of the first 5 mass_to_flipper_length_ratio values
print([____.____ for entry in labeled_entries[____]])
แก้ไขและรันโค้ด