问题
方法
# (1) [] -> () foo = (x for x in range(100)) # (2) 通过yield方式创建 def bar_gen(): for i in range(100): yield i # 调用yield就返回一个生成器对象 bar = bar_gen() for i in range(100): x = next(bar) # 通过next()方法每次获得一个生成数据 print(x, end=' ') print() def bar_gen1(): x = 1 yield x+1 # 返回数据并暂停, 下一次next()的时候恢复到这里继续执行 yield x+2 yield x+3 bar1 = bar_gen1() x1 = next(bar1) x2 = next(bar1) x3 = next(bar1) print(x1, x2, x3) # 2 3 4