You can download this code by clicking the button below.
This code is now available for download.
This function uses the zip_longest function from the itertools module to merge multiple iterable objects into an iterator. If the longest input iterable is exhausted, fillvalue is used to fill the shorter iterable.
Technology Stack : itertools
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=None):
# 从内置库中选取zip_longest,它来自itertools模块,用于合并多个可迭代对象
# 当最长的输入迭代器耗尽时,用fillvalue填充较短的迭代器
def _all_iterable(obj):
return all(hasattr(obj, '__iter__') for obj in args)
def _zipper(*iterables):
iterators = [iter(it) for it in iterables]
while True:
result = []
for it in iterators:
try:
result.append(next(it))
except StopIteration:
iterators.remove(it)
if not iterators:
return
result.append(fillvalue)
yield tuple(result)
if _all_iterable(args):
return _zipper(*args)
else:
raise TypeError("Not all arguments are iterable")