開始使用免費開始

使用 dataclasses

讓我們把上一個練習建立的 WeightEntry dataclass 派上用場。你會為 weight_log 中的每個紀錄建立一個 WeightEntry 實例,接著使用我們新增的 mass_to_flipper_length_ratio 屬性來進行計算。以下是 WeightEntry dataclass 的提醒:

@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 的空清單。
  • 使用 tuple 展開的方式迭代 weight_log,分別取出 speciesflipper_lengthbody_masssex
    • 對於每個紀錄,建立一個新的 WeightEntry dataclass 實例並附加到 labeled_entries
  • 使用清單生成式列印前 5 個 mass_to_flipper_length_ratio 的值。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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[____]])
編輯並執行程式碼