压缩两个迭代器直到它们都耗尽

与内置函数 zip() 类似,itertools.zip_longest 将继续迭代超过两个迭代中较短的迭代的末尾。

from itertools import zip_longest
a = [i for i in range(5)] # Length is 5
b = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # Length is 7
for i in zip_longest(a, b):
    x, y = i  # Note that zip longest returns the values as a tuple
    print(x, y)

可以传递一个可选的 fillvalue 参数(默认为''),如下所示:

for i in zip_longest(a, b, fillvalue='Hogwash!'):
    x, y = i  # Note that zip longest returns the values as a tuple
    print(x, y)

在 Python 2.6 和 2.7 中,这个函数叫做 itertools.izip_longest