Merging Iterables with Fillvalue using zip_longest

  • Share this:

Code introduction


The function merges multiple iterable objects into an iterator, if elements in some iterable objects run out, fillvalue is used to fill.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 将多个可迭代对象合并成一个迭代器,如果某个可迭代对象中的元素用完,则用fillvalue填充
    zipped = zip(*iterables)
    return iter(lambda x: tuple(itertools.chain(x, [fillvalue] * (len(iterables) - len(x)))), zipped)                
              
Tags: