始める無料で始める

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 の各エントリから 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[____]])
コードを編集して実行