Python 迭代器和生成器
2016-05-05 00:33
507 查看
list1 = iter([11,22,33,44,55,66,77,88,99]) print (list1.__next__()) print (list1.__next__()) 结果: 11 22 结论:迭代器,只能取next的值。 应用:
fp = open("ha.bak") for line in fp: print (line.strip('\n')) fp.close() with open("ha.bak",'r') as fp: for line1 in fp: print (line1.strip()) 在for line in fp中也可以使用for line in fp.readlines()函数,但是这样读起来效率很低,for line in fp可以像迭代器一样,一条一条的读入到内存中,不需要一次性读入。 生成器:
def fab(max): n = 0 a = 0 b = 1 while n < max: yield b #print (b) a, b = b, a + b n = n + 1 f = fab(5) print (f.__next__()) print (f.__next__()) print (f.__next__()) print (f.__next__()) print (f.__next__()) print (f.__next__()) 使用yield参数相当于返回这样一个值(b),但是这样的返回不是作为函数的结束而返回的,而是像中断一样,下次你再访问的时候,还是从刚才那个中断开始。
1
1
2
3
5
Traceback (most recent call last):
File "D:/Python/day3/Test.py", line 20, in <module>
print (f.__next__())
StopIteration
查看另外一个例子“
def withdraw(account): while account > 0: account -= 100 yield 1 print ("withdraw again") f = withdraw(500) print (f.__next__()) print ("first next") print (f.__next__()) print ("second next") print (f.__next__()) print ("third next") print (f.__next__()) print ("fourth next") print (f.__next__()) print ("fifth next")
1
first next
withdraw again
1
second next
withdraw again
1
third next
withdraw again
1
fourth next
withdraw again
1
fifth next
在这个例子中,每次取100最多只能有五次取钱的机会。在print (f.__next__())函数中间可以增加其他的程序代码,而当迭代器再次回来运行的时候,还是从刚才保存的状态 开始。这样一个生产迭代器的函数叫做生成器。
相关文章推荐
- 关于python的for语句
- libpython2.7.so.1.0 cannot open的解决方法
- 使用Python判断质数(素数)的简单方法讲解
- Python环境下搭建属于自己的pip源的教程
- Python使用Paramiko模块编写脚本进行远程服务器操作
- Python中内建函数的简单用法说明
- Python核心编程-第五章
- python 错误、异常
- python 测试与调试(test)
- Python爬虫: 抓取One网页上的每日一话和图
- python的json模块,针对decimal类型直接dumps报错
- Python文件读写基础
- Python 类与元类的深度挖掘 II
- Python-量化分析之路
- python(二)拾遗
- [Python]经典教程
- python2 type()函数 isinstance()函数
- pythondb操作
- 安装Numpy,Scipy,Matplotlib的步骤及下载地址(亲测有效)
- python效率提升:ctypes的初次使用