Zip Longest Iterator with Fillvalue

  • Share this:

Code introduction


This function returns an iterator that yields elements taken from the provided iterable objects. If an iterable is exhausted, it is filled with fillvalue.


Technology Stack : collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    # 从内置库中选取:collections
    from collections import deque

    iterators = [deque(iter(a)) for a in args]
    longest = max(iterators, key=len)
    for i in longest:
        for it in iterators:
            yield next(it, fillvalue)

# JSON输出                
              
Tags: