开始使用免费开始使用

使用 dataclass

让我们把上一个练习中创建的 WeightEntry 数据类用起来。我们将为 weight_log 中的每条记录创建一个 WeightEntry 实例,然后使用我们添加的 mass_to_flipper_length_ratio 属性进行计算。下面是 WeightEntry 数据类的回顾。

@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 数据类实例,并追加到 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[____]])
编辑并运行代码