Combining Iterables with Fill Value

  • Share this:

Code introduction


This function takes multiple iterable objects, combines them into tuples, and if one of the iterable objects has been fully iterated, it fills with a specified fill value.


Technology Stack : Iterators, generators

Code Type : Iterator function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    将可迭代对象组合成元组,如果最短的输入迭代完,其他迭代器还有剩余,则用fillvalue填充。

    Args:
        *args: 可变数量的可迭代对象。
        fillvalue: 当最短的输入迭代完时填充的值。

    Returns:
        一个迭代器,生成由输入的每个元素组成的元组,如果某个输入迭代完,则用fillvalue填充。
    """
    iters = [iter(arg) for arg in args]
    while True:
        result = []
        for iter_ in iters:
            try:
                result.append(next(iter_))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)

# JSON描述