1. Learn
  2. /
  3. Courses
  4. /
  5. Python のデータ型

Connected

Exercise

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

Instructions

100 XP
  • labeled_entries という空のリストを作成します。
  • タプルの展開を使って、weight_log の各エントリから species、flipper_length、body_mass、sex を取り出しながら反復します。
    • 各エントリについて、新しい WeightEntry dataclass のインスタンスを作成し、labeled_entries に追加します。
  • リスト内包表記を使って、最初の 5 件の mass_to_flipper_length_ratio の値のリストを表示します。