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__()

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

你可能感兴趣的:(Python 生成器)