Iteratori Python
Iterators programmā Python ir objekts, kas tiek izmantots, lai iterētu pār iterējamiem objektiem, piemēram, sarakstiem, korežiem, diktiem un kopām. Python iteratoru objekts tiek inicializēts, izmantojot iter() metodi. Tas izmanto Nākamais() iterācijas metode.
- __iter__(): metode iter() tiek izsaukta iteratora inicializācijai. Tas atgriež iteratora objektu __next__(): Nākamā metode atgriež nākamo iterējamā vērtību. Ja mēs izmantojam for cilpu, lai šķērsotu jebkuru iterējamu objektu, iekšēji tā izmanto metodi iter(), lai iegūtu iteratora objektu, kas tālāk izmanto next() metodi, lai atkārtotu. Šī metode rada StopIteration, lai signalizētu par iterācijas beigām.
Python iter() piemērs
Python3
string> => 'GFG'> ch_iterator> => iter> (string)> print> (> next> (ch_iterator))> print> (> next> (ch_iterator))> print> (> next> (ch_iterator))> |
Izvade:
G F G
Iteratora izveide un cilpa, izmantojot iter() un next()
Zemāk ir vienkāršs Python iterators, kas izveido iteratora veidu, kas atkārtojas no 10 līdz noteiktam ierobežojumam. Piemēram, ja limits ir 15, tad drukā 10 11 12 13 14 15. Un, ja limits ir 5, tad nedrukā neko.
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>>> |