生成器generator
从高天视频处学习
简单示例
- 知识点1 使用yield定义生成器函数,调用得到生成器对象
- 知识点2
def gen(num): while num > 0: yield num num -= 1 return # g是一个生成器对象 g = gen(5) print(next(g)) print("---------") print(next(g)) print("test done") for i in g: print(i) '''output 5 分割线 4 test done 3 2 1 '''
详细解释和生成器的send()
def gen(num): while num > 0: tmp = yield num if tmp is not None: num = tmp num -= 1 return # g是一个生成器对象 g = gen(5) print(next(g)) # 等价 print(g.send(None)) print("---------") print(next(g)) print("test done") print(f"send:{g.send(10)}") # for loop 等价 i=next(g) loop for i in g: print(i) '''output 5 分割线 4 test done send:9 8 7 6 5 4 3 2 1'''
留言