Python 生成器

方法一

b = (x for x in range(10))
print(next(b))

方法二

def creatNum():
    a,b = 0,1
    for i in range(5):
        yield b #生成器
        a,b = b, a+b
a = creatNum()
for num in a:
    print(num)
'''多任务 协程'''
def test1():
    while True:
        print('----1----')
        yield None

def test2():
    while True:
        print('----2----')
        yield None

t1 = test1()
t2 = test2()
while True:
    t1.__next__()
    t2.__next__()

生成器 生成多个值,不是现在生成,需要的时候生成,不占用大量内存空间

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。