Merging Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


This function merges multiple iterable objects into an iterator. If one of the iterable objects is exhausted, it is filled with fillvalue until all iterable objects have been traversed.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    # 使用内置库itertools的zip_longest函数,用于将多个可迭代对象合并为一个迭代器,如果其中某个可迭代对象已经遍历完成,则用fillvalue填充
    from itertools import zip_longest

    def iter_helper(*args):
        for arg in args:
            for item in arg:
                yield item

    for items in zip_longest(*args):
        yield list(iter_helper(*items))                
              
Tags: