Zip Longest Iterator Function

  • Share this:

Code introduction


This function takes any number of iterable arguments and returns a new iterator. If one of the iterators is exhausted, the others are filled with fillvalue until all iterators are exhausted.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty :


                
                    
def zip_longest(*args, fillvalue=None):
    # 将可变数量的迭代器组合成一个迭代器,其中较短的迭代器会使用fillvalue填充
    iters = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)

# JSON表示