शुरू करेंमुफ़्त में शुरू करें

Dataclasses का उपयोग

आईए पिछले अभ्यास में बनाई गई WeightEntry dataclass को काम में लें. हम weight_log की हर एंट्री के लिए एक WeightEntry इंस्टेंस बनाएँगे और फिर जो mass_to_flipper_length_ratio प्रॉपर्टी जोड़ी थी, उससे कैलकुलेशन करेंगे. यहाँ हमारी 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

यह अभ्यास पाठ्यक्रम का हिस्सा है

Python में डेटा टाइप्स

पाठ्यक्रम देखें

अभ्यास निर्देश

  • labeled_entries नाम की एक खाली लिस्ट बनाएँ.
  • weight_log पर iterate करें और tuple expansion का उपयोग करके species, flipper_length, body_mass, sex अलग करें.
    • हर एंट्री के लिए एक नया WeightEntry dataclass इंस्टेंस बनाएँ और उसे labeled_entries में append करें.
  • List comprehension का उपयोग करके शुरुआती 5 mass_to_flipper_length_ratio वैल्यूज़ की लिस्ट प्रिंट करें.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

# 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[____]])
कोड संपादित करें और चलाएँ