MulaiMulai sekarang secara gratis

Using dataclasses

Let's put our WeightEntry dataclass we created in the prior exercise to use. We'll create an instance of the WeightEntry for each entry in the weight_log and then use the mass_to_flipper_length_ratio property we added to perform the calculation. Here is a reminder of our 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

Latihan ini adalah bagian dari kursus

Data Types in Python

Lihat Kursus

Petunjuk latihan

  • Create an empty list called labeled_entries.
  • Iterate over the weight_log entries using tuple expansion to break out species, flipper_length, body_mass, sex.
    • Append a new WeightEntry dataclass instance for each entry to labeled_entries.
  • Print a list of the first 5 mass_to_flipper_length_ratio values using a list comprehension.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# 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[____]])
Edit dan Jalankan Kode