Merging Iterators with FillValue

  • Share this:

Code introduction


This function merges multiple iterators into one iterator. If one of the iterators runs out of elements, it fills the remaining positions with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """将多个迭代器合并为一个迭代器,如果其中一个迭代器耗尽,则用fillvalue填充。

    Args:
        *args: 可变数量的迭代器。
        fillvalue: 填充值,当迭代器耗尽时使用。

    Returns:
        一个迭代器,包含所有输入迭代器的元素,如果某个迭代器耗尽,则用fillvalue填充。
    """
    from itertools import zip_longest

    return zip_longest(*args, fillvalue=fillvalue)                
              
Tags: