迭代器限制:不能向后移动、不能回到开始、再次迭代只能创建另一个迭代对象。
反序迭代工具:reversed()将返回一个反序访问的迭代器。
python中提供的迭代模块:itertools模块
第一、迭代序列:
点击(此处)折叠或打开
- >>> myTuple = ('xyz',123,34.56)
- >>> myTuple
- ('xyz', 123, 34.56)
- >>> i = iter(myTuple)
- >>> i.next()
- 'xyz'
- >>> i.next()
- 123
- >>> i.next()
- 34.56
点击(此处)折叠或打开
- fetch = iter(seq)
- while True:
- try:
- i = fetch.next()
- except StopIteration:
- break
- do_something_to(i)
字典的迭代实例:
点击(此处)折叠或打开
- >>> legends = {('poe','author'):(1809,1849,1976),('Gaudi','architect'):(1852,1906,1987),('Freud','psychoanalyst'):(1856,1939,1990)}
- >>> for eachLegend in legends:
- print 'Name:%s\tOccupation:%s' % eachLegend
- print 'Birth:%s\tDeath:%s\tAlbum:%s\n' % legends[eachLegend]
-
- Name:poe Occupation:author
- Birth:1809 Death:1849 Album:1976
- Name:Gaudi Occupation:architect
- Birth:1852 Death:1906 Album:1987
- Name:Freud Occupation:psychoanalyst
- Birth:1856 Death:1939 Album:1990
文件执行过程:
点击(此处)折叠或打开
- myFile = open('config-win.txt')
- for eachLine in myFile:
- print eachLine