当有多个不同的序列(container)需要进行迭代时,常见的方式是写多个for循环语句,或者编写如下的代码:
def chain(*iterables):
# chain('ABC', 'DEF') --> A B C D E E
for it in iterables:
for element in it:
yield element
itertools模块提供了chain方法,可以组合多个不同类型的容器依次迭代。如下:
>>> from itertools import chain
>>> a = [1, 2, 3, 4]
>>> b = ['x', 'y', 'z']
>>> for x in chain(a, b):
print(x)
...
1
2
3
4
x
y
z
>>>