Implementation of zip_longest with Fillvalue

  • Share this:

Code introduction


The function takes multiple iterable objects as input, and when the longest iterable object is traversed, it fills the shorter iterable objects with fillvalue until all iterable objects are traversed.


Technology Stack : collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 从内置库collections中选取,实现zip_longest功能
    from collections import deque
    iterators = [deque(iterable) for iterable in iterables]
    while iterators:
        yield [iterable.popleft() for iterable in iterators if iterable]
    while iterators:
        iterators[0].append(fillvalue)
        yield [iterable[0] for iterable in iterators]                
              
Tags: