<每日一题>题目4:for循环套生成器的面试题
2024-08-28 03:10:07
题目:
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]
最新文章
- js 数组删去重复的加上没有的元素
- ES7之Decorators实现AOP示例
- Spring实战学习笔记之SpEL表达式
- poj1789 Truck History
- 拓展Jquery对象,实现Post提交并跳转
- 【数据结构】通用的最小堆(最大堆)D-ary Heap
- Quoit Design
- 知识库系统/知识管理系统 WCP
- Spark笔记-treeReduce、reduce、reduceByKey
- C#相关知识总结
- Rust语言
- AdminIII连接linux Postgresql过程中的几个小问题
- 【刷题】【LeetCode】007-整数反转-easy
- 枚举转map
- Quartz.Net进阶之四:CronTrigger 详述
- 光盘作为yum源
- win10系统如何关掉系统自动更新
- Donsen法则
- aaronyang的百度地图API之LBS云与.NET开发 Javascript API 2.0【把数据存到LBS云1/2】
- python基础学习1-网络爬虫程序中的代理IP设置
热门文章
- Linux关闭重启系统
- JavaScript深入之类数组对象与arguments(转载)
- 关于微信小程序的一些总结
- sendmail 出现 My unqualified host name的解决办法
- MAT in eclipse - memory analyzer
- [SDOI2017]数字表格 (莫比乌斯反演)
- 工欲善其事,必先利其器——React Native的 IDE
- Linux 进程通信之:内存共享(Shared Memory)(转,好文章)
- 小程序之背景音乐——wx.backgroundAudioManager
- python-字符串的处理