生成器

def fib(num):
    a, b = 0, 1
    index = 0
    while index < num:
        yield a
        a, b = b, a+b
        index += 1
    return 'ok...'

f = fib(100)

while True:
    try:
        print(next(f))
    except Exception as e:
        print(e.value)
        break
        
# for num in f:
#     print(num)

 

def fib(num):
    a, b = 0, 1
    index = 0
    while index < num:
        temp = yield a
        print('temp:',temp)
        a, b = b, a+b
        index += 1
f = fib(20)
ret = next(f)
print(ret)
ret2 = f.send('test')
print(ret2)

 

import time

def task1():
    while True:
        print('----1----')
        time.sleep(0.1)
        yield

def task2():
    while True:
        print('----2----')
        time.sleep(0.1)
        yield

def main():
    t1 = task1()
    t2 = task2()
    while True:
        next(t1)
        next(t2)

if __name__ == '__main__':
    main()

 

posted @ 2018-09-13 16:50  Woowo  阅读(142)  评论(0编辑  收藏  举报