零基础学python-13.1 迭代器简介与文件迭代器

来源:互联网 发布:derby数据库优缺点 编辑:程序博客网 时间:2024/06/05 05:42

1.迭代器简介

可迭代对象:列表、元组、字符串

迭代工具:for循环、列表解析、in成员关系测试、map内建函数

下面是一些例子:

>>> for item in (1,3,4,5):print(item)1345>>> for alpha in 'abcde':print(alpha)abcde>>> for item in [1,2,3,4]:print(item)1234>>> 


上面的例子都是使用for循环结合in成员关系测试来迭代列表、元组与字符串

 

2.文件迭代器

说到文件迭代,一般会使用for与readline结合起来

>>> handler=open('output_file.txt')>>> handler.readline()'abcd\n'>>> handler.readline()'efgh\n'>>> handler.readline()'ijklstrstr\n'>>> handler.readline()'nn'>>> handler.readline()''


 

>>> handler=open('output_file.txt')>>> for line in handler.readlines():print(line)abcdefghijklstrstrnn>>> 


注意:我们上面第一个程序一直调用handler.readline(),如果到了末尾,他一直返回空,而我们使用for加上handler.readlines(),如果到达底部,则直接停止

在文件里面也有一个内建函数__next__可以达到类似的效果

>>> handler=open('output_file.txt')>>> handler.__next__ ()'abcd\n'>>> handler.__next__ ()'efgh\n'>>> handler.__next__ ()'ijklstrstr\n'>>> handler.__next__ ()'nn'>>> handler.__next__ ()Traceback (most recent call last):  File "<pyshell#35>", line 1, in <module>    handler.__next__ ()StopIteration>>> handler.close ()>>> 


但是有一点需要注意,使用__next__的时候,当到达底部,他会报错

__next__是通过捕捉StopIteration来确定是否离开

 

最后我们来讨论一下性能的问题:

1.当文件过大的时候怎么读取(至少100M)

因为handler.readlines()方法是一次性把整个文件加载到内存里面去,所以这个方法不适合

在这种情况下,一般是一行行的来读取,我们下面提供两种方法:

>>> for line in handler:print(line,end='')abcdefghijklstrstrnn>>> 
>>> handler=open('output_file.txt')>>> while True:line=handler.readline()if not line:breakprint(line,end='')abcdefghijklstrstrnn>>> handler.close ()>>> 


在上面的两种方法中,我们更加推荐第一种for...in...,这种方法更加快捷而且简洁

 

总结:这一章节主要简单介绍了迭代器,以及文件迭代器的使用,性能的简单介绍

 

这一章节就说到这里,谢谢大家

------------------------------------------------------------------

点击跳转零基础学python-目录


 

0 0