# 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>>> Išvestis: 10 11 12 13 14 15 Iteravimas per integruotą iteruojamą naudojant iter() metodą Tolesnėse iteracijose iteracijos būsena ir iteratoriaus kintamasis yra valdomi viduje (mes jo nematome), naudojant iteratoriaus objektą, kad būtų galima pereiti per integruotą iteraciją, pvz. sąrašą , kortele , diktatas ir kt. 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]))> | Išvestis: 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 ir Python iterator skiriasi. Pagrindinis skirtumas tarp jų yra tas, kad Python programoje iteruojama negali išsaugoti iteracijos būsenos, o iteratoriuose išsaugoma dabartinės iteracijos būsena. Pastaba: Kiekvienas iteratorius taip pat yra kartojamas, bet ne kiekvienas iteratorius yra „Python“ iteratorius. Skaityti daugiau - Skirtumas tarp iteruojamo ir iteratoriaus. Iteravimas Iterable Kiekvieno iteruojamo elemento kartojimas. Python3 tup> => (> 'a'> ,> 'b'> ,> 'c'> ,> 'd'> ,> 'e'> )> for> item> in> tup:> > print> (item)> | Išvestis: a b c d e Iteravimas iteratoriuje 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))> | Išvestis: Inside loop: a b c Outside loop: d e Naudojant iteratorių gaunama StopIteration klaida „Iterable“ programoje „Python“ gali būti kartojama kelis kartus, tačiau iteratoriai iškelia StopIteration Error, kai visi elementai jau yra iteruojami. Čia mes bandome gauti kitą elementą iš iteratoriaus po to, kai bus užbaigta for-ciklas. Kadangi iteratorius jau išnaudotas, iškeliama StopIteration išimtis. Tuo tarpu naudojant iteraciją, galime kartoti kelis kartus naudodami for ciklus arba gauti elementus naudodami indeksavimą. 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))> | Išvestis: 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 Straipsniai
Kategorija
|