You can download this code by clicking the button below.
This code is now available for download.
This function merges multiple iterable objects. When one iterator finishes, it uses fillvalue to fill the rest.
Technology Stack : Built-in library
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=None):
"""将多个可迭代对象合并成一个迭代器,如果最短的迭代器先遍历完,则使用fillvalue填充。
Args:
*args: 可变数量的可迭代对象。
fillvalue: 如果最短的迭代器先遍历完,用于填充的值。
Returns:
zip_longest迭代器,包含所有输入迭代器的元素。
"""
iters = [iter(arg) for arg in args]
while True:
result = []
for it in iters:
try:
result.append(next(it))
except StopIteration:
result.append(fillvalue)
if not all(result):
break
return result