问题
遍历一个可迭代对象中的所有元素,但是却不想使用for循环。
解决方案
为了手动地遍历可迭代对象,使用 next()
函数并在代码中捕获 StopIteration
异常。 比如:
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
x = next(it) # 获得下一个值
print(x, end = ' ')
except StopIteration: # 遇到StopIteration就退出循环
break
1 2 3 4 5
通常来讲, StopIteration
用来指示迭代的结尾。 手动使用 next()
函数的话,可以通过返回一个指定值来标记结尾,比如 None 。 比如:
it = iter([1, 2, 3, 4, 5])
while True:
x = next(it, None)
if x is None:
break
print(x, end = ' ')
1 2 3 4 5
讨论
大多数情况下,我们会使用 for 循环语句,遍历一个可迭代对象。 但是,偶尔也需要对迭代做更加精确的控制,了解底层迭代机制是必要的。
下面的交互示例,演示了迭代期间所发生的基本细节:
items = [1, 2, 3]
it = iter(items)
print(next(it))
1
print(next(it))
2
print(next(it))
3
print(next(it))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
网友评论