Combining Iterables with FillValue Using zip_longest

  • Share this:

Code introduction


The function combines multiple iterable objects into an iterator, filling with fillvalue if an iterable runs out, until all iterable objects are exhausted.


Technology Stack : zip, while loop, iterator, generator

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 将多个可迭代对象组合成一个迭代器,如果某个可迭代对象耗尽,则以fillvalue填充
    zipped = zip(*iterables)
    while True:
        yield zipped
        for i, iterable in enumerate(iterables):
            if len(iterable) == len(zipped):
                break
            if not iterable:
                iterables[i] = iter([fillvalue])
            else:
                iterable = iter(iterable)
        else:
            break