1. Học hỏi
  2. /
  3. Khoa Học
  4. /
  5. Các kiểu dữ liệu trong Python

Connected

Bài tập

Sử dụng dataclass

Hãy đưa WeightEntry dataclass mà bạn đã tạo ở bài trước vào sử dụng. Bạn sẽ tạo một instance WeightEntry cho mỗi bản ghi trong weight_log, rồi dùng thuộc tính mass_to_flipper_length_ratio mà ta đã thêm để thực hiện phép tính. Dưới đây là phần nhắc lại về 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

Hướng dẫn

100 XP
  • Tạo một list rỗng tên labeled_entries.
  • Lặp qua các bản ghi trong weight_log và dùng mở rộng tuple để tách species, flipper_length, body_mass, sex.
    • Thêm (append) một instance dataclass WeightEntry mới cho mỗi bản ghi vào labeled_entries.
  • In ra danh sách 5 giá trị mass_to_flipper_length_ratio đầu tiên bằng list comprehension.