반복가능 자료형 & 반복자

참고 : 널널한 교수의 코딩 클래스


(1) 반복자

  • 데이터를 순차적으로 꺼내내는 객체

  • 반복가능 객체 ex)

    • list, tuple, range…
  • iter()함수에 넣어서, “반복자 객체”로 만들 수 있음

    • next()__next()__라는 메소드를 사용하여 꺼냄

    • 다 꺼내고 난 뒤, next 수행 시 StopIteration 이라는 예외 발생!


list

Example

>>> l=[1,2,3]
>>> l_iter = iter(l)
>>> l_iter
<list_iterator object at 0x000001779271EC70>

>>> next(l_iter)
1
>>> next(l_iter)
2
>>> next(l_iter)
3

>>> next(l_iter)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> l=[1,2,3]
>>> l_iter = iter(l)
>>> l_iter.__next__()
1
>>> l_iter.__next__()
2
>>> l_iter.__next__()
3
>>> l_iter.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration


range

range 또한 iter()를 통해 반복자 객체로 만들 수 있음

Example

>>> r_iter = iter(range(1,4))
>>> r_iter.__next__()
1
>>> r_iter.__next__()
2
>>> r_iter.__next__()
3
>>> r_iter.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration


(2) 반복자 객체 생성하기

다음의 2가지 메소드를 반드시 멤버로 가져야!

  • 1) __iter__()
    • 반복자 객체 자신(self)을 반환해야
  • 2) __next__()
    • 루프가 돌 때마다, 지정 값 반환


Example 1 : 홀수 값을 반환하는 객체

oddcount.py

class OddCounter:
    def __init__(self,n=1):
        self.n=n

    def __iter__(self):
        return self
    
    def __next__(self):
        if self.n<20:
            value = self.n
            self.n +=2
            return value
        raise StopIteration

odd_counter = OddCounter()
print(odd_counter.__next__())
print(odd_counter.__next__())
print(odd_counter.__next__())
PS C:\Users\LSH\Desktop\advanced_python> python oddcount.py
1
3
5


Example 2 : 홀수 값을 반환하는 객체 & 조건

oddcount.py

class OddCounter:
    def __init__(self,n=1):
        self.n=n

    def __iter__(self):
        return self
    
    def __next__(self):
        if self.n<20:
            value = self.n
            self.n +=2
            return value
        raise StopIteration

odd_counter = OddCounter()
for _ in range(12):
    print(odd_counter.__next__())

PS C:\Users\LSH\Desktop\advanced_python> python oddcount.py
1
3
5
7
9
11
13
15
17
19
Traceback (most recent call last):
  File "oddcount.py", line 17, in <module>
    print(odd_counter.__next__())
  File "oddcount.py", line 13, in __next__
    raise StopIteration
StopIteration