पाठ 14 / 49
कॉम्प्रिहेंशन और नेस्टेड डेटा
Comprehensions से एक पठनीय line में lists, dicts और sets बनाएँ, और nested data से records model करें।
List comprehension
List comprehension किसी iterable से नई सूची बनाता है, वैकल्पिक रूप से if से फ़िल्टर किया हुआ।
squares = [n * n for n in range(6)]
evens = [n for n in range(20) if n % 2 == 0]
print(squares)
print(evens)Dict और set comprehension
यही विचार dict और set पर भी लागू होता है — बस ब्रैकेट बदलें।
squares = {n: n * n for n in range(5)}
unique_lens = {len(w) for w in ["hi", "bye", "ok"]}
print(squares)
print(unique_lens)नेस्टेड डेटा संरचनाएँ
लिस्ट और dict नेस्ट हो सकते हैं: dicts की लिस्ट (रिकॉर्ड्स), या lists का dict (समूहीकृत डेटा) — असल प्रोग्राम में बहुत आम।
त्वरित जाँच: `[n for n in range(5) if n % 2 == 0]` क्या देता है?
- [0, 2, 4]
- [1, 3]
- [0, 1, 2, 3, 4]
- [0, 2, 4, 6]
Answer
[0, 2, 4] — केवल सम संख्याएँ 0-4 `if` फ़िल्टर से गुज़रती हैं।