Zip Longest Function for Merging Iterables with Fillvalue

  • Share this:

Code introduction


The function is used to merge multiple iterable objects. If some iterable objects are shorter than the others, it fills them with the fillvalue.


Technology Stack : Built-in library itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    # 从内置库itertools中选取zip_longest函数,用于合并多个可迭代对象,如果长度不一致,则以fillvalue填充
    iterator = iter(args)
    longest = max(len(lst) for lst in args, default=0)
    for i in range(longest):
        yield tuple(next(iterator, fillvalue) for _ in args)

# JSON格式的代码描述