Aan de slagGa gratis aan de slag

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

Deze oefening maakt deel uit van de cursus

Data Types in Python

Cursus bekijken

Oefeninstructies

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

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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[____]])
Code bewerken en uitvoeren