python -yield理解

参考:https://foofish.net/iterators-vs-generators.html

从网上看到一个面试题,求最后的输出结果:

def add(n, i):
return n+i
def test():
for i in range(4):
yield i
g = test()

for n in [1, 10, 5]:
g=(add(n, i) for i in g)
print(list(g))

输出结果:
[1, 2, 3, 4]
[]
[]
list数据类型强转也可以读取生成器的值,第一次循环n=1的时候 生成器g已经被读取了一遍,所以后面
# n =10,n=5的时候生成器不能再被读取 就出现了空的list []
 
t = test()
for n in [1, 10, 5]:
t = (add(n, i) for i in t)
print(list(t))
输出结果:
[15, 16, 17, 18]
n=1, t = (add(n, i) for i in t) 若取生成器值应为[1,2,3,4]
n=10, t = (add(n, i) for i in (add(n, i) for i in t)),若取值应为[20,21,22,23]
n=5, t=(add(n, i) for i in (add(n, i) for i in (add(n, i) for i in t))),若取值[15, 16, 17, 18]


test()因为函数里面没有return,而是yield 生成器对象,表示test()是一个生成器,g=test()并不会立即执行,
只有当它被隐示或者显示的调用next时才能真正执行test()里面的代码;
生成器的值只能被读取一次;



注意:以上均是自己的个人理解,有问题请指教。






猜你喜欢

转载自www.cnblogs.com/t-ae/p/10743217.html