Combining Iterables with Fillvalue

  • Share this:

Code introduction


Combines multiple iterable objects into tuples, using fillvalue to fill in if the shortest iterable is exhausted first.


Technology Stack : Iterators, Generators

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """将多个可迭代对象组合成一个个元组,如果最短的迭代对象先遍历完,则使用fillvalue填充。

    Args:
        *args: 可变数量的可迭代对象。
        fillvalue: 用于填充较短的可迭代对象的值。

    Returns:
        一个迭代器,返回组合的元组。

    """
    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)