迭代器用于从集合中取出元素;而生成器用于“凭空”生成元素。
在 Python 中,使用了 yield 的函数被称为生成器(generator)。
练习:输出1到10乘以2的值.
def gen10():
for i in range(10):
yield 2*(i+1)
g = gen10()
for i in g:
print i
output:
2
4
6
8
10
12
14
16
18
20
迭代器有两个基本的方法:iter() 和 next()