# 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>>> Lähtö: 10 11 12 13 14 15 Iteroidaan sisäänrakennetun iteroitavan kautta käyttämällä iter()-menetelmää Seuraavissa iteraatioissa iteroinnin tilaa ja iteraattorimuuttujaa hallitaan sisäisesti (emme näe sitä) käyttämällä iteraattoriobjektia kulkemaan sisäänrakennetun iterablen yli, kuten lista , monikko , sanele , jne. Python 3 # 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]))> | Lähtö: List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345 Iterable vs Iterator Python-iterable ja Python-iteraattori ovat erilaisia. Suurin ero niiden välillä on, että Pythonissa iteroitavissa oleva iteraatio ei voi tallentaa iteraation tilaa, kun taas iteraattoreissa nykyisen iteraation tila tallennetaan. Huomautus: Jokainen iteraattori on myös iteroitava, mutta jokainen iteroitava ei ole iteraattori Pythonissa. Lue lisää – Ero iteroitavan ja iteraattorin välillä. Iterointi iteroitavalla Toisto iteroitavan jokaisen kohteen kohdalla. Python 3 tup> => (> 'a'> ,> 'b'> ,> 'c'> ,> 'd'> ,> 'e'> )> for> item> in> tup:> > print> (item)> | Lähtö: a b c d e Iterointi iteraattorissa Python 3 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))> | Lähtö: Inside loop: a b c Outside loop: d e StopIteration Erration -virhe iteraattoria käytettäessä Pythonissa iteroitavaa voidaan iteroida useita kertoja, mutta iteraattorit nostavat StopIteration Error -virheen, kun kaikki kohteet on jo iteroitu. Tässä yritämme saada seuraavan elementin iteraattorista for-silmukan valmistumisen jälkeen. Koska iteraattori on jo käytetty loppuun, se herättää StopIteration Exceptionin. Kun taas iteroitavaa käytettäessä voimme iteroida useita kertoja käyttämällä for-silmukkaa, tai voimme saada kohteita indeksoinnin avulla. Python 3 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))> | Lähtö: 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
Top Artikkelit
Luokka
Mielenkiintoisia Artikkeleita
|