Merging Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


The function is used to merge iterables of different lengths into an iterator. If some iterables are shorter, they are filled with the fillvalue.


Technology Stack : zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 从Python内置库中选取zip_longest函数,用于将可迭代对象合并,如果长度不等,则以fillvalue填充

    def _all_equal_length(*iterables):
        return all(len(iterable) == len(iterables[0]) for iterable in iterables)

    def _zip_generator():
        iters = iter(iterables)
        result = []
        for item in iters:
            result.append(next(item))
        yield result

    if _all_equal_length(*iterables):
        return zip(*iterables)
    else:
        while True:
            result = _zip_generator()
            try:
                yield result
            except StopIteration:
                return

                 
              
Tags: