Concatenating Unequal-Length Iterables with FillValue

  • Share this:

Code introduction


The function is used to concatenate multiple iterable objects whose lengths may not be equal. If an iterable object is exhausted, fillvalue is used to fill the remaining positions.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 从内置库itertools中选取zip_longest函数,用于合并多个迭代器,如果迭代器长度不等,则以fillvalue填充
    from itertools import zip_longest

    def iter_func():
        for iterable in iterables:
            for item in iterable:
                yield item

    zipped = zip_longest(iter_func(), fillvalue=fillvalue)
    return list(zipped)                
              
Tags: