Iterating Through Iterables with Fillvalue

  • Share this:

Code introduction


The function takes any number of iterable objects and returns an iterator that takes as many elements as possible from each iterable and fills the remaining positions with fillvalue when the shortest iterable is exhausted.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 从 itertools 库中选取 zip_longest 函数,用于合并多个迭代器,并在最短的迭代器结束时用 fillvalue 填充
    iterators = []
    for iterable in iterables:
        iterators.append(iter(iterable))
    while True:
        yield tuple(map(next, iterators))
        for i, iterator in enumerate(iterators):
            try:
                iterators[i] = iter(next(iterator))
            except StopIteration:
                iterators[i] = iter([fillvalue])                
              
Tags: