பாடம் 1 / 5 · Advanced Python · படிக்க 2 min · புதுப்பிக்கப்பட்டது
Iterators, zip, enumerate
for loop உண்மையில என்ன செய்யுது, ரெண்டு lists-ஐ சேர்ந்து நடக்கிறது, உங்க objects-ஐ loop பண்ணக்கூடியதா ஆக்குறது.
for loop நடக்கக்கூடிய எதுவும் iterable. Loop அதுகிட்ட iter() வெச்சு ஒரு iterator கேட்கும், அப்புறம் iterator StopIteration raise பண்ற வரைக்கும் next() கூப்பிடும். நீங்களே கையால செய்யலாம்:
colours = ["red", "green"]
it = iter(colours)
print(next(it))
print(next(it))
try:
next(it)
except StopIteration:
print("No more items")
red
green
No more items
zip, enumerate
names = ["Priya", "Arun", "Meena"]
marks = [87, 73, 94]
for i, (name, m) in enumerate(zip(names, marks), start=1):
print(i, name, m)
print(dict(zip(names, marks)))
1 Priya 87
2 Arun 73
3 Meena 94
{'Priya': 87, 'Arun': 73, 'Meena': 94}
zip() பல iterables-ல இருந்து items-ஐ ஜோடி சேர்க்கும், சின்னது முடிஞ்சதும் நிக்கும். enumerate() ஒரு counter சேர்க்கும். ரெண்டும் சேர்ந்தா கிட்டத்தட்ட எல்லா range(len(...)) loops-க்கும் மாற்று; dict(zip(keys, values)) ஒரே படியில dictionary கட்டும்.
உங்க சொந்த iterator
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
for n in Countdown(3):
print(n)
3
2
1
Note
Iterator முடிஞ்சதும் தீர்ந்துடும். அதே zip(...) object மேல ரெண்டு தடவை loop பண்ணா ரெண்டாவது loop எதுவும் செய்யாது. Lists-ஐ எத்தனை தடவை வேணும்னாலும் loop பண்ணலாம், ஏன்னா ஒவ்வொரு loop-ம் புது iterator கேட்கும்.
list(zip([1, 2, 3], ["a", "b"])) என்ன தரும்?
இப்போ இதை செஞ்சு பாருங்க
- Dishes list-ல இருந்தும் prices list-ல இருந்தும் enumerate, zip வெச்சு எண் போட்ட menu print பண்ணுங்க.
- Limit வரைக்கும் 0, 2, 4 ... தர்ற
EvenNumbers(limit)iterator class எழுதுங்க.
Create a free account to save your progress, or sign in.