python interview

#Interview questions 
def demo():
     for i in range(4 ):
         yield i

g=demo()

g1=(i for i in g)
g2=(i for i in g1)

print(list(g1))
print(list(g2))

result:
[0, 1, 2, 3]
[]




def add(n,i):
    return n+i

def test():
    for i in range(4):
        yield i

g=test()
for n in [1,3,10]:
    g=(add(n,i) for i in g)

print(list(g))
result:
[30, 31, 32, 33]

#A generator can only be taken once 
# The generator never executes when it does not find the value it wants 
# When it executes, it must be based on all variable values ​​at the time of execution

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324866288&siteId=291194637