#通过元组推导式
w = (i for i in range(10))
print(w)
#通过yield关键字
def work():
for i in range(10):
yield i
w = work()
print(w)
#通过yield from关键字,后面接可迭代对象,可以实现生成器的嵌套
def work():
yield from [1,2,3]
w = work()
print(w)
读取生成器元素
'''
生成器每次执行到yield那一行结束,下一次yield下一行开始
1.通过next(generator)或generator.__next__()读取下一元素
2.通过generator.send(object),send可以传入数据到函数,默认传入为None
3.通过for循环读取
'''
def work():
for i in range(10):
res = yield i
print(res)
w = work()
print(next(w))
print(w.__next__())
print(w.send('hi'))
for i in w:
print(i)