生成器有两种:
生成器表达式:(x*x for x in [1,2,3])
yield表达式:
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
迭代器,有next()方法可以通过next()不断地获得下一个元素的就是迭代器;生成器也是迭代器。
可以用于for ...in...循环的就是可迭代,比如 dict list tuple str ,迭代器,
dict、list、str、tuple可通过iter()函数获得迭代器,
Python的for循环本质上就是通过不断调用迭代器的next()函数实现的
for x in [1, 2, 3, 4, 5]:
pass
实际上完全等价于:
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
except StopIteration:
# 遇到StopIteration就退出循环
Break