Python의 반복자
Python의 반복자는 목록, 튜플, 사전 및 집합과 같은 반복 가능한 개체를 반복하는 데 사용되는 개체입니다. Python 반복자 객체는 다음을 사용하여 초기화됩니다. 반복() 방법. 그것은 다음() 반복 방법.
- __iter__(): iter() 메서드는 반복자의 초기화를 위해 호출됩니다. 이는 반복자 객체를 반환합니다. __next__(): next 메서드는 반복 가능 항목에 대한 다음 값을 반환합니다. for 루프를 사용하여 반복 가능한 객체를 순회할 때 내부적으로 iter() 메서드를 사용하여 반복자 객체를 가져오고, 추가로 next() 메서드를 사용하여 반복합니다. 이 메서드는 반복 종료를 알리기 위해 StopIteration을 발생시킵니다.
Python iter() 예
파이썬3
string> => 'GFG'> ch_iterator> => iter> (string)> print> (> next> (ch_iterator))> print> (> next> (ch_iterator))> print> (> next> (ch_iterator))> |
출력 :
G F G
iter() 및 next()를 사용하여 반복자 생성 및 반복
다음은 10부터 지정된 제한까지 반복하는 반복자 유형을 생성하는 간단한 Python 반복자입니다. 예를 들어 한계가 15이면 10 11 12 13 14 15가 인쇄됩니다. 한계가 5이면 아무것도 인쇄되지 않습니다.
파이썬3
# 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)> |
산출:
10 11 12 13 14 15
iter() 메서드를 사용하여 내장 iterable을 반복합니다.
다음 반복에서 반복 상태와 반복자 변수는 다음과 같이 내장된 반복 가능 항목을 탐색하기 위해 반복자 객체를 사용하여 내부적으로 관리됩니다(우리는 볼 수 없습니다). 목록 , 튜플 , 딕셔너리 , 등.
파이썬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]))> |
산출:
List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345
반복 가능 대 반복자
Python iterable과 Python iterator는 다릅니다. 이들 사이의 주요 차이점은 Python의 iterable은 반복 상태를 저장할 수 없는 반면, 반복기에서는 현재 반복의 상태가 저장된다는 것입니다.
메모: 모든 반복자는 반복 가능하지만 모든 반복 가능이 Python의 반복자는 아닙니다.
더 읽어보세요 – iterable과 iterator의 차이점.
Iterable에서 반복하기
iterable의 각 항목을 반복합니다.
파이썬3
tup> => (> 'a'> ,> 'b'> ,> 'c'> ,> 'd'> ,> 'e'> )> for> item> in> tup:> > print> (item)> |
산출:
a b c d e
반복자 반복
파이썬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))> |
산출:
Inside loop: a b c Outside loop: d e
반복자를 사용하는 동안 StopIteration 오류 발생
Python의 Iterable은 여러 번 반복될 수 있지만 모든 항목이 이미 반복되면 반복자는 StopIteration Error를 발생시킵니다.
여기서는 for 루프가 완료된 후 반복자에서 다음 요소를 가져오려고 합니다. 반복자가 이미 소진되었으므로 StopIteration 예외가 발생합니다. 반면 iterable을 사용하면 for 루프를 사용하여 여러 번 반복하거나 인덱싱을 사용하여 항목을 가져올 수 있습니다.
파이썬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))> |
산출:
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