Bắt đầu ngayBắt đầu miễn phí

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

Bài tập này là một phần của khóa học

Các kiểu dữ liệu trong Python

Xem khóa học

Hướng dẫn bài tập

  • 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.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

# 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[____]])
Chỉnh sửa và Chạy Mã