关于生成器基本用法请参考详解Python生成器函数和生成器对象的原理和用法
>>> def f(): yield from 'abcdefg' #使用yield表达式创建生成器 >>> x = f() >>> next(x) 'a' >>> next(x) 'b' >>> for item in x: #输出x中的剩余元素 print(item, end=' ') c d e f g >>> def gen(): yield 1 yield 2 yield 3 >>> x, y, z = gen() #生成器对象支持序列解包
生成器对象还支持使用send()方法传入新值,从而改变后续生成的数据,这时要对yield表达式稍微改写一下。
>>> def gen(start, end): i = start while i < end: v = (yield i) if v: i = v else: i += 1 >>> g = gen(1, 101) >>> next(g) 1 >>> g.__next__() 2 >>> g.send(9) #传入新值,改变后续生成的数据 9 >>> next(g) 10
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有