迭代应用

it2025-10-29  16

迭代

 

>>> L = ['Jay','sandra','micheal','Candy'] >>> s = iter(L) >>> s.__next__() 'Jay' >>> s.__next__() 'sandra' >>> s.__next__() 'micheal' >>> s.__next__() 'Candy' >>> s.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration

  

 

1 文件操作

     我们读取文件的时候,会用到一个readline()方法,其实它就是一个迭代器,它会返回当前的数据,然后自动的调用内置的next()方法来让文件的读取头自动的移动到当前的下面一行,准备下次的读取,到达文件末尾时,就会返回空字符串.

  以下方法读取速度快,占用内存小适合读取大文件。

for s in open('test.txt'): print(s)

 

2 For 循环

for i in range(5): print(i)

他的处理过程是:

>>> L = [0,1,2,3,4] >>> I = iter(L) >>> I.__next__() 0 >>> I.__next__() 1 >>> I.__next__() 2 >>> I.__next__() 3 >>> I.__next__() 4

 

3列表解析

>>> L = [x+1 for x in range(10)] >>> L [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 

4迭代序列索引  

>>> L =['a','b','c','d'] >>> for i in range(len(L)): ... print(L[i]) ... a b c d

  

  

  

  

 

 

转载于:https://www.cnblogs.com/luoye00/p/5980122.html

相关资源:变分迭代法应用
最新回复(0)