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という空のリストを作成します。- タプルの展開を使って、
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[____]])