python yield 생성기 기본 내용 및 피보나치 수열 실현

기본 내용
#           yield      
#                         ,           
#           ,       (      ,        ),        ,              
#          ,   yield      ,   return      

#         ,            generator.py
li = [[1], [2, 3], [4, 5,6]]
def generator(li):
    for i in li:
        for j in i:
            yield j

>>> from generator import li, generator
>>> generator(li)
0x7f57a4eff0a0>  #          
>>> for i in generator(li):
...     print(i)
... 
1
2
3
4
5
6

#       ,        ,        ,     
>>> y = (i*i for i in range(5))
>>> y
 at 0x7f57a4eff1a8>
>>> next(y)
0
>>> next(y)
1
>>> list(y)
[4, 9, 16]

생성기 피보나치 수열 실현
# generator.py
def fibs():
    a = 0
    b = 1
    while True:
        a, b = b, a+b 
        yield a

>>> from generator import fibs
>>> f = fibs()
>>> f
0x7fdb5a7c20f8>
>>> next(f)
1
>>> next(f)
1
>>> next(f)
2
>>> next(f)
3
>>> next(f)
5

좋은 웹페이지 즐겨찾기