பாடம் 2 / 5 · Advanced Python · படிக்க 2 min · புதுப்பிக்கப்பட்டது

Generators

yield வெச்சு ஒரு நேரத்துக்கு ஒரு value உருவாக்குறது — பெரிய, முடிவில்லாத sequences-க்கு.

Iterator class எழுத ஒரு டஜன் lines ஆகும். Generator அதையே ஒரு சாதாரண function-ல return-க்கு பதிலா yield வெச்சு செய்யும். ஒவ்வொரு yield-ம் ஒரு value கொடுத்து, அடுத்த value கேட்கிற வரைக்கும் function-ஐ அங்கேயே நிறுத்தி வைக்கும்.

python
def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(3):
    print(x)

gen = countdown(2)
print(next(gen), next(gen))
Output
3
2
1
2 1

Generator expressions

python
print(sum(n * n for n in range(1, 1_000_001)))

marks = [72, 45, 91, 38]
print(sum(m for m in marks if m >= 50))
print(any(m < 40 for m in marks), all(m > 30 for m in marks))
Output
333333833333500000
163
True True

Square brackets-க்கு பதிலா round brackets போட்டா list-க்கு பதிலா generator கிடைக்கும். மேல பத்து லட்சம் squares-ஓட கூட்டுத்தொகை பத்து லட்சம் item list-ஐ கட்டவே இல்ல: ஒவ்வொரு square-ம் உருவாகி, கூட்டப்பட்டு, மறக்கப்படுது. any(), all() பதில் தெரிஞ்சதுமே சீக்கிரமா நின்னுடும்.

முடிவே இல்லாத sequences

python
from itertools import islice

def evens():
    n = 0
    while True:
        yield n
        n += 2

print(list(islice(evens(), 5)))
Output
[0, 2, 4, 6, 8]

Note

முடிவில்லாத generator பாதுகாப்பானது, ஏன்னா கேட்கிற வரைக்கும் எதுவும் கணக்கிடப்படாது. itertools.islice முதல் சிலதை மட்டும் எடுக்கும். Standard itertools module-ல இன்னும் நிறைய building blocks இருக்கு: count, cycle, chain, groupby.

[x * 2 for x in data]-க்கும் (x * 2 for x in data)-க்கும் என்ன வித்தியாசம்?

இப்போ இதை செஞ்சு பாருங்க

  1. Fibonacci எண்களை முடிவில்லாம yield பண்ற fibonacci() generator எழுதி, islice வெச்சு முதல் 15-ஐ print பண்ணுங்க.
  2. ஒரு file-ஐ படிச்சு, காலி இல்லாத lines-ஐ மட்டும் yield பண்ற generator எழுதுங்க.

Create a free account to save your progress, or sign in.