题目:

 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))

  分析:

  我们知道生成器函数和生成器表达式都很"懒",只要你不找它取值它就不执行.

  函数从上到下开始执行,一直到13行都没开始,13行list()函数找g要值,9-10行的生成器表达式才开始执行,我们将9-10行拆开:

 n =1
g = (add(n,i) for i in g)
n =10
g = (add(n,i) for i in g)
n =5
g = (add(n,i) for i in g)

  根据执行顺序,1-4行都是生成器表达式,在13行找此时6行要值的时候,1-4行都还未执行,我们将表达式都写在6行,得到:

 n =5
g = (add(n,i) for i in (add(n,i) for i in (add(n,i) for i in test())))

  从里面往外面执行,

  test() == (0,1,2,3)

  (add(n,i) for i in test()) == (5,6,7,8)

  (add(n,i) for i in (add(n,i) for i in test())) ==(10,11,12,13)

  (add(n,i) for i in (add(n,i) for i in (add(n,i) for i in test()) )) ==(15,16,17,18)

  g=(15,16,17,18)

  list(g) == [15,16,17,18]

  输出结果:

 [15, 16, 17, 18]

最新文章

  1. js 数组删去重复的加上没有的元素
  2. ES7之Decorators实现AOP示例
  3. Spring实战学习笔记之SpEL表达式
  4. poj1789 Truck History
  5. 拓展Jquery对象,实现Post提交并跳转
  6. 【数据结构】通用的最小堆(最大堆)D-ary Heap
  7. Quoit Design
  8. 知识库系统/知识管理系统 WCP
  9. Spark笔记-treeReduce、reduce、reduceByKey
  10. C#相关知识总结
  11. Rust语言
  12. AdminIII连接linux Postgresql过程中的几个小问题
  13. 【刷题】【LeetCode】007-整数反转-easy
  14. 枚举转map
  15. Quartz.Net进阶之四:CronTrigger 详述
  16. 光盘作为yum源
  17. win10系统如何关掉系统自动更新
  18. Donsen法则
  19. aaronyang的百度地图API之LBS云与.NET开发 Javascript API 2.0【把数据存到LBS云1/2】
  20. python基础学习1-网络爬虫程序中的代理IP设置

热门文章

  1. Linux关闭重启系统
  2. JavaScript深入之类数组对象与arguments(转载)
  3. 关于微信小程序的一些总结
  4. sendmail 出现 My unqualified host name的解决办法
  5. MAT in eclipse - memory analyzer
  6. [SDOI2017]数字表格 (莫比乌斯反演)
  7. 工欲善其事,必先利其器——React Native的 IDE
  8. Linux 进程通信之:内存共享(Shared Memory)(转,好文章)
  9. 小程序之背景音乐——wx.backgroundAudioManager
  10. python-字符串的处理