Combining Iterables with Fillvalue using zip_longest

  • Share this:

Code introduction


The function combines multiple iterable objects into an iterator. If an iterable is exhausted, it is filled with a specified fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 将多个可迭代对象合并成一个迭代器,如果某个可迭代对象耗尽,则用fillvalue填充
    from itertools import zip_longest

    def generate():
        for iterable in iterables:
            for element in iterable:
                yield element

    return zip_longest(generate(), fillvalue=fillvalue)                
              
Tags: