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
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_logvà dùng mở rộng tuple để táchspecies,flipper_length,body_mass,sex.- Thêm (append) một instance dataclass
WeightEntrymới cho mỗi bản ghi vàolabeled_entries.
- Thêm (append) một instance dataclass
- 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[____]])