使用 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,分別取出species、flipper_length、body_mass、sex。- 對於每個紀錄,建立一個新的
WeightEntrydataclass 實例並附加到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[____]])