BaşlayınÜcretsiz Başlayın

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

Bu egzersiz

Data Types in Python

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

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

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# 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[____]])
Kodu Düzenle ve Çalıştır