壓縮兩個迭代器直到它們都耗盡

與內建函式 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