python-生成器,filter的理解
来源:互联网 发布:视频特效编辑软件 编辑:程序博客网 时间:2024/06/06 02:29
代码1:
def nums(): i = 3 yield i while True: i = i + 2 yield idef isNot(n): return lambda x : x % n > 0def prime(): yield 2 L = nums() while True: m = next(L) yield m g = lambda x:x%m > 0 L = filter(isNot(m), L)group = prime()for i in range(20): print(next(group))
代码2:
def nums(): i = 3 yield i while True: i = i + 2 yield idef isNot(n): return lambda x : x % n > 0def prime(): yield 2 L = nums() while True: m = next(L) yield m g = lambda x:x%m > 0 L = filter(g, L)group = prime()for i in range(20): print(next(group))
代码设计目的为输出素数
代码1输出符合预期:输出素数;但是代码2却只输出了大于1的奇数
这是为什么?
因为在代码2中 L = filter(ig, L) 中,filter函数返回的是一个生成器(无穷数列),g中的m即为循环中的m。在next时才取出数m = next(L),输出3下一个循环m = next(L),L的定义为
def nums(): i = 3 yield i while True: i = i + 2if g(i): yield i
也就是
def nums(): i = 3 yield i while True: i = i + 2if i%m >0 yield i
执行完m = next(L)后,此时m已经变为5了
下一个循环时m = next(L),L的定义为
def nums(): i = 3 yield i while True: i = i + 2if g(i): if g(i): yield i
此时m已经为7。
然而在代码1中m传入isNot函数中后为n,n不再变。因此符合预期
阅读全文
0 0
- python-生成器,filter的理解
- 对Python生成器的理解
- python的迭代器、生成器、yield理解
- python学习笔记--理解生成器
- 深入理解Python中的生成器
- 深入理解Python中的生成器
- 深入理解Python中的生成器
- 【Python】迭代器和生成器理解
- 深入理解python中的生成器
- 对python yield 生成器的理解 --个人笔记
- 深入理解python的生成器表达式和列表解析
- 对生成器的理解
- Python的生成器
- python生成器的几个问题
- python的生成器
- Python的生成器
- Python的生成器表达式与生成器函数
- Python 生成器及高阶函数 filter map reduce
- 如何查找进程id号,并且使它停止?
- 8月8日小结
- Python当中的a += a 与 a = a + a 的区别,可变类型与不可变类型的数据类型,引用传参
- js获取form表单所有数据的简单方法
- Mysql自定义split的functoin
- python-生成器,filter的理解
- 如何利用神经网络和Python生成指定模式的密码
- 读书大杂烩
- JZOJ1749. 城市交通 (2017.8B组)
- 浅析volatile关键字
- 手动创建两个文本文件text1.txt,text2.txt,要求编程创建text3.txt,实现text1.txt和text2.txt文件中除去首行和末尾对应的数据相加
- 冒泡排序、选择排序、插入排序、希尔排序、快速排序、归并排序六大排序大总结
- 文件的上传与下载之方式3:Spring MVC
- codeforces 404B Marathon(模拟)