摘要:在本节中,你将学习关于 Python 可迭代对象(iterables)和迭代器(iterators)的知识。
Python 可迭代对象简介
在 Python 中,可迭代对象是一个包含零个、一个或多个元素的对象。可迭代对象具有一次返回一个元素的能力。
由于这一特性,你可以使用 for
循环来遍历可迭代对象。
事实上range()
函数就是一个可迭代对象,因为你可以遍历其结果:
for index in range(3):
print(index)
输出:
0
1
2
此外,字符串(string
)是一个可迭代对象,因为你可以使用 for
循环来遍历它:
str = 'Iterables'
for ch in str:
print(ch)
输出:
I
t
e
r
a
b
l
e
s
列表(lists)和元组(tuples)也是可迭代对象,因为你可以对它们进行遍历。例如:
ranks = ['high', 'medium', 'low']
for rank in ranks:
print(rank)
经验法则是,如果你知道可以遍历某个对象,那么它就是一个可迭代对象。
什么是迭代器
一个可迭代对象是可以被遍历的。而迭代器是执行遍历操作的代理(agent)。
要从可迭代对象中获取迭代器,你可以使用 iter()
函数。例如:
colors = ['red', 'green', 'blue']
colors_iter = iter(colors)
一旦你有了迭代器,就可以使用 next()
函数从可迭代对象中获取下一个元素:
colors = ['red', 'green', 'blue']
colors_iter = iter(colors)
color = next(colors_iter)
print(color)
输出:
red
每次调用 next()
函数时,它都会返回可迭代对象中的下一个元素。例如:
colors = ['red', 'green', 'blue']
colors_iter = iter(colors)
color = next(colors_iter)
print(color)
color = next(colors_iter)
print(color)
color = next(colors_iter)
print(color)
输出:
red
green
blue
如果没有更多元素,而你仍然调用了 next()
函数,将会引发一个异常。
colors = ['red', 'green', 'blue']
colors_iter = iter(colors)
color = next(colors_iter)
print(color)
color = next(colors_iter)
print(color)
color = next(colors_iter)
print(color)
# 引发异常
color = next(colors_iter)
print(color)
这个示例首先展示了 colors
列表中的三个元素,然后引发了一个异常:
red
green
blue
Traceback (most recent call last):
File "iterable.py", line 15, in <module>
color = next(colors_iter)
StopIteration
迭代器是有状态的,这意味着一旦你从迭代器中消费了一个元素,该元素就消失了。
换句话说,一旦你完成了对迭代器的遍历,迭代器就变为空了。如果你再次遍历它,它将不会返回任何内容。
由于你可以遍历一个迭代器,因此迭代器也是一个可迭代对象。
这可能会让人感到困惑。例如:
colors = ['red', 'green', 'blue']
iterator = iter(colors)
for color in iterator:
print(color)
输出:
red
green
blue
如果你调用 iter()
函数并将一个迭代器传递给它,它将返回相同的迭代器。
稍后,你将学习如何创建可迭代对象。
总结
可迭代对象是可以被遍历的对象。可迭代对象具有一次返回一个其元素的能力。
迭代器是执行迭代操作的代理。它是有状态的。并且,迭代器也是一个可迭代对象。
使用
iter()
函数可以从可迭代对象中获取迭代器,使用next()
函数可以从可迭代对象中获取下一个元素。