You can download this code by clicking the button below.
This code is now available for download.
This function combines iterable objects of different lengths into tuples, using a specified fillvalue to fill if an iterable is exhausted.
Technology Stack : Built-in functions, iterators
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=0):
"""将可迭代对象组合成元组,如果最短的序列耗尽,则用fillvalue填充。
Args:
*args: 可变数量的可迭代对象。
fillvalue: 当序列耗尽时用于填充的值。
Returns:
迭代器,产生元组。
"""
iterators = [iter(arg) for arg in args]
longest = max(len(it) for it in iterators)
for i in range(longest):
yield tuple(next(it, fillvalue) for it in iterators)