Asosiy matnga o'tish
ITIT Interview
Python

Iteratorlar va generatorlar

Iterable va iterator farqi, iterator protokoli, yield, generator funksiyalar va ifodalar, lazy hisoblash, yield from, send va itertools.

O'rganildi: 0 / 5
Progress

Bu nima?

  • Iterable — ustidan yurish mumkin bo'lgan obyekt: list, str, dict, fayl. __iter__ metodi bor.
  • Iterator — elementlarni birma-bir beradigan obyekt. __next__ metodi bor, tugaganda StopIteration tashlaydi.
nums = [1, 2, 3]          # iterable
it = iter(nums)           # iterator
next(it)   # 1
next(it)   # 2
next(it)   # 3
next(it)   # StopIteration

for sikli ichkarida aynan shunday ishlaydi: iter() chaqiradi, keyin StopIteration gacha next().

Iterator bir martalik: tugagach, qaytadan yurib bo'lmaydi.

Generator funksiya

yield ishlatgan funksiya generator qaytaradi. U qiymatlarni lazy — so'ralganda birma-bir hisoblaydi va har yield da to'xtab, holatini saqlaydi:

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

for x in countdown(3):
    print(x)          # 3, 2, 1

gen = countdown(2)
next(gen)   # 2
next(gen)   # 1
next(gen)   # StopIteration

Katta fayllar bilan ishlash

def read_large_file(path):
    with open(path, encoding="utf-8") as f:
        for line in f:                # fayl ham lazy iterator
            yield line.strip()

def errors_only(lines):
    for line in lines:
        if "ERROR" in line:
            yield line

# 10 GB fayl — xotirada faqat bitta qator
for line in errors_only(read_large_file("app.log")):
    print(line)

Cheksiz ketma-ketlik

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

from itertools import islice
list(islice(fibonacci(), 10))   # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Generator ifoda

squares = (x * x for x in range(1_000_000))   # deyarli xotira egallamaydi
sum(squares)
List comprehension [...]Generator ifoda (...)
HisoblanishDarhol, hammasiLazy, birma-bir
XotiraO(n)O(1)
Qayta ishlatishMumkinBir martalik
Indeks, len()BorYo'q

yield from

def flatten(nested):
    for item in nested:
        if isinstance(item, list):
            yield from flatten(item)     # ichki generatorga topshirish
        else:
            yield item

list(flatten([1, [2, [3, 4]], 5]))   # [1, 2, 3, 4, 5]

O'z iteratoringiz

class Range:
    def __init__(self, start, stop):
        self.current, self.stop = start, stop

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.stop:
            raise StopIteration
        value = self.current
        self.current += 1
        return value

Ko'pincha generator funksiya yozish ancha qisqa.

itertools

from itertools import chain, groupby, islice, product, permutations, combinations, count

list(chain([1, 2], [3]))              # [1, 2, 3]
list(combinations("abc", 2))          # [('a','b'), ('a','c'), ('b','c')]
list(product([0, 1], repeat=2))       # [(0,0), (0,1), (1,0), (1,1)]
for city, group in groupby(sorted(users, key=k), key=k): ...   # avval saralash shart

Intervyu savollari

Ushbu sahifada