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अलग करें.- हर एंट्री के लिए एक नया
WeightEntrydataclass इंस्टेंस बनाएँ और उसे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[____]])