生成器面试题

def demo():
    for i in range(2):
        yield i
g = demo()
g1 = (i for i in g)
g2 = (i for i in g1)
print(list(g1))
print(list(g2))  #执行list(g2),调用g1的值,g1是个生成器,g1里面的值已经被取干净了,所以没有值可以取

 

def add(n,i):
    return n+i
def test():
    for i in range(4):
        yield i
g = test()  #返回一个生成器
# for n in [1,10]:
#     g = (add(n,i) for i in g)
n = 1
g = (add(n,i) for i in g)
n = 10
g = (add(n,i) for i in g)
print(list(g))

 

转载于:https://www.cnblogs.com/li33232/p/11447461.html

你可能感兴趣的:(生成器面试题)