Merging Iterables with Fillvalue using zip_longest

  • Share this:

Code introduction


This function merges multiple iterable objects into an iterator. If an iterable object is exhausted, it is filled with a specified fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """将多个可迭代对象合并为一个迭代器,如果某个可迭代对象耗尽,则使用fillvalue填充。
    
    Args:
        *args: 任意数量的可迭代对象。
        fillvalue: 如果某个可迭代对象耗尽,用于填充的值。
    
    Returns:
        一个迭代器,它返回一个元组,其中包含来自每个输入可迭代对象的元素,如果某个可迭代对象耗尽,则用fillvalue填充。
    """
    from itertools import zip_longest as zip_longest
    return zip_longest(*args, fillvalue=fillvalue)                
              
Tags: