Iterátory v Pythonu
Iterátor v Pythonu je objekt, který se používá k iteraci přes iterovatelné objekty, jako jsou seznamy, n-tice, diktáty a množiny. Objekt Python iterators je inicializován pomocí iter() metoda. Používá se další() metoda pro iteraci.
- __iter__(): Metoda iter() je volána pro inicializaci iterátoru. To vrátí objekt iterátoru __next__(): Další metoda vrátí další hodnotu pro iterovatelný. Když použijeme cyklus for k procházení jakéhokoli iterovatelného objektu, interně používá metodu iter() k získání objektu iterátoru, který dále používá metodu next() k iteraci. Tato metoda vyvolá StopIteration, aby signalizovala konec iterace.
Příklad Python iter().
Python3
string> => 'GFG'> ch_iterator> => iter> (string)> print> (> next> (ch_iterator))> print> (> next> (ch_iterator))> print> (> next> (ch_iterator))> |
Výstup :
G F G
Vytváření a opakování iterátoru pomocí iter() a next()
Níže je jednoduchý iterátor Pythonu, který vytvoří typ iterátoru, který iteruje od 10 do daného limitu. Pokud je například limit 15, vypíše 10 11 12 13 14 15. A pokud je limit 5, nevytiskne nic.
Python3
# A simple Python program to demonstrate> # working of iterators using an example type> # that iterates from 10 to given value> # An iterable user defined type> class> Test:> > # Constructor> > def> __init__(> self> , limit):> > self> .limit> => limit> > # Creates iterator object> > # Called when iteration is initialized> > def> __iter__(> self> ):> > self> .x> => 10> > return> self> > # To move to next element. In Python 3,> > # we should replace next with __next__> > def> __next__(> self> ):> > # Store current value ofx> > x> => self> .x> > # Stop iteration if limit is reached> > if> x>> self> .limit:> > raise> StopIteration> > # Else increment and return old value> > self> .x> => x> +> 1> ;> > return> x> # Prints numbers from 10 to 15> for> i> in> Test(> 15> ):> > print> (i)> # Prints nothing> for> i> in> Test(> 5> ):> > print> (i)> |
Výstup:
10 11 12 13 14 15
Iterace přes vestavěnou iterovatelnost pomocí metody iter().
V následujících iteracích je stav iterace a proměnná iterátoru spravována interně (nevidíme ji) pomocí objektu iterátoru k procházení vestavěným iterátorem jako seznam , tuple , diktát , atd.
Python3
# Sample built-in iterators> # Iterating over a list> print> (> 'List Iteration'> )> l> => [> 'geeks'> ,> 'for'> ,> 'geeks'> ]> for> i> in> l:> > print> (i)> > # Iterating over a tuple (immutable)> print> (> '
Tuple Iteration'> )> t> => (> 'geeks'> ,> 'for'> ,> 'geeks'> )> for> i> in> t:> > print> (i)> > # Iterating over a String> print> (> '
String Iteration'> )> s> => 'Geeks'> for> i> in> s :> > print> (i)> > # Iterating over dictionary> print> (> '
Dictionary Iteration'> )> d> => dict> ()> d[> 'xyz'> ]> => 123> d[> 'abc'> ]> => 345> for> i> in> d :> > print> (> '%s %d'> %> (i, d[i]))> |
Výstup:
List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345
Iterovatelné vs Iterator
Python iterable a Python iterator se liší. Hlavní rozdíl mezi nimi je, že iterovatelný v Pythonu nemůže uložit stav iterace, zatímco v iterátorech se uloží stav aktuální iterace.
Poznámka: Každý iterátor je také iterovatelný, ale ne každý iterátor je iterátor v Pythonu .
Přečtěte si více – Rozdíl mezi iterovatelným a iterátorem .
Iterování na Iterable
Iterování na každé položce iterovatelného.
Python3
tup> => (> 'a'> ,> 'b'> ,> 'c'> ,> 'd'> ,> 'e'> )> for> item> in> tup:> > print> (item)> |
Výstup:
a b c d e
Iterace na iterátoru
Python3
tup> => (> 'a'> ,> 'b'> ,> 'c'> ,> 'd'> ,> 'e'> )> # creating an iterator from the tuple> tup_iter> => iter> (tup)> print> (> 'Inside loop:'> )> # iterating on each item of the iterator object> for> index, item> in> enumerate> (tup_iter):> > print> (item)> > # break outside loop after iterating on 3 elements> > if> index> => => 2> :> > break> # we can print the remaining items to be iterated using next()> # thus, the state was saved> print> (> 'Outside loop:'> )> print> (> next> (tup_iter))> print> (> next> (tup_iter))> |
Výstup:
Inside loop: a b c Outside loop: d e
Získání chyby StopIteration při používání iterátoru
Iterovatelné v Pythonu lze iterovat vícekrát, ale iterátory vyvolávají chybu StopIteration Error, když jsou všechny položky již iterovány.
Zde se pokoušíme získat další prvek z iterátoru po dokončení smyčky for. Protože je iterátor již vyčerpán, vyvolá výjimku StopIteration. Zatímco pomocí iterovatelného můžeme iterovat vícekrát pomocí cyklu for nebo můžeme získat položky pomocí indexování.
Python3
iterable> => (> 1> ,> 2> ,> 3> ,> 4> )> iterator_obj> => iter> (iterable)> print> (> 'Iterable loop 1:'> )> # iterating on iterable> for> item> in> iterable:> > print> (item, end> => ','> )> print> (> '
Iterable Loop 2:'> )> for> item> in> iterable:> > print> (item, end> => ','> )> print> (> '
Iterating on an iterator:'> )> # iterating on an iterator object multiple times> for> item> in> iterator_obj:> > print> (item, end> => ','> )> print> (> '
Iterator: Outside loop'> )> # this line will raise StopIteration Exception> # since all items are iterated in the previous for-loop> print> (> next> (iterator_obj))> |
Výstup:
Iterable loop 1: 1,2,3,4, Iterable Loop 2: 1,2,3,4, Iterating on an iterator: 1,2,3,4, Iterator: Outside loop Traceback (most recent call last): File 'scratch_1.py', line 21, in print(next(iterator_obj)) StopIteration