8.11.4 使用迭代器

8.11.4 使用迭代器
===序列===
正如先前提到的, 迭代 Python 的序列对象和你想像的一样:

myTuple = (123, ‘xyz’, 45.67)
i = iter(myTuple)
i.next()
123
i.next()
‘xyz’
i.next()
45.67
i.next()
Traceback (most recent call last):
File “”, line 1, in ?
StopIteration
如果这是一个实际应用程序, 那么我们需要把代码放在一个 try-except 块中. 序列现在会自
动地产生它们自己的迭代器, 所以一个 for 循环:
for i in seq:
do_something_to(i)
实际上是这样工作的:
fetch = iter(seq)
while True:
try:
i = fetch.next()
except StopIteration:
Edit By Vheavens
Edit By Vheavens
break
do_something_to(i)
不过, 你不需要改动你的代码, 因为 for 循环会自动调用迭代器的 next() 方法(以及监视
StopIteration 异常).
===字典===
字典和文件是另外两个可迭代的 Python 数据类型. 字典的迭代器会遍历它的键(keys).
语句 for eachKey in myDict.keys() 可以缩写为 for eachKey in myDict , 例如:
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: Freud Occupation: psychoanalyst
Birth: 1856 Death: 1939 Album: 1990
Name: Poe Occupation: author
Birth: 1809 Death: 1849 Album: 1976
Name: Gaudi Occupation: architect
Birth: 1852 Death: 1906 Album: 1987
另外, Python 还引进了三个新的内建字典方法来定义迭代: myDict.iterkeys() (通过 keys 迭
代), myDict.itervalues() (通过 values 迭代), 以及 myDicit.iteritems() (通过 key/value 对
来迭代). 注意, in 操作符也可以用于检查字典的 key 是否存在 , 之前的布尔表达式
myDict.has_key(anyKey) 可以被简写为 anyKey in myDict .
===文件===
文件对象生成的迭代器会自动调用 readline() 方法. 这样, 循环就可以访问文本文件的所有
行 . 程 序 员 可 以 使 用 更 简 单 的 for eachLine in myFile 替 换 for eachLine in
myFile.readlines() :
Edit By Vheavens
Edit By Vheavens
myFile = open(‘config-win.txt’)
for eachLine in myFile:
… print eachLine, # comma suppresses extra \n

[EditorWindow]
font-name: courier new
font-size: 10
myFile.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值