Python Implementation of itertools.zip_longest

  • Share this:

Code introduction


The function implements the functionality of itertools.zip_longest, which combines multiple iterable objects into a tuple iterator, filling with a specified fillvalue if any iterable is exhausted.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 从内置库中选取的包:itertools
    # 功能:zip_longest 函数会返回一个迭代器,它将元素组合成元组,如果迭代器中的某些元素已经耗尽,则用 fillvalue 填充。

    def _next():
        for iterable in iterables:
            if iterable:
                yield next(iterable)

    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while True:
        result = []
        for it in iterators:
            result.append(next(it, fillvalue))
        if sentinel not in result:
            for it in iterators:
                if it is not None:
                    it.send(sentinel)
            break

    return result                
              
Tags: