--Yield is written in the loop of the generator function --The part of the generator function other than the loop is called only once --Generator function returns an iterator --Repeated elements can be obtained from the iterator by the next method. --The more you call the next method, the more values you can generate
fibonacci.py
#!/usr/bin/python
#Define a generator
def fibonacci():
a = 0 #Initial setting
b = 1 #Initial setting
while True:
yield b #Write yield inside the loop of the generator function
a, b = b, a + b
#Generator returns iterator
fib = fibonacci()
#Put each element of the iterator into an array in order in list comprehension
fib_array = [fib.next() for i in range(10)]
print fib_array
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Recommended Posts