# 生成器(Generators)

1. def generator_function():
2. for i in range(10):
3. yield i
4. for item in generator_function():
5. print(item)
6. # Output: 0
7. # 1
8. # 2
9. # 3
10. # 4
11. # 5
12. # 6
13. # 7
14. # 8
15. # 9

1. # generator version
2. def fibon(n):
3. a = b =1
4. for i in range(n):
5. yield a
6. a, b = b, a + b

1. for x in fibon(1000000):
2. print(x)

1. def fibon(n):
2. a = b =1
3. result =[]
4. for i in range(n):
5. result.append(a)
6. a, b = b, a + b
7. return result

1. def generator_function():
2. for i in range(3):
3. yield i
4. gen = generator_function()
5. print(next(gen))
6. # Output: 0
7. print(next(gen))
8. # Output: 1
9. print(next(gen))
10. # Output: 2
11. print(next(gen))
12. # Output: Traceback (most recent call last):
13. # File "<stdin>", line 1, in <module>
14. # StopIteration

1. my_string ="Yasoob"
2. next(my_string)
3. # Output: Traceback (most recent call last):
4. # File "<stdin>", line 1, in <module>
5. # TypeError: str object is not an iterator

1. my_string ="Yasoob"
2. my_iter = iter(my_string)
3. next(my_iter)
4. # Output: 'Y'