python -yield理解
生活随笔
收集整理的这篇文章主要介绍了
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()里面的代码;
生成器的值只能被读取一次;
注意:以上均是自己的个人理解,有问题请指教。
转载于:https://www.cnblogs.com/t-ae/p/10743217.html
总结
以上是生活随笔为你收集整理的python -yield理解的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: [工具向]__androidstudio
- 下一篇: python学习Day14 带参装饰器