Merging Iterables with Fillvalue

  • Share this:

Code introduction


Create an iterator that merges multiple iterable objects, and fills with fillvalue if the objects have different lengths.


Technology Stack : Built-in functions

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """将多个可迭代对象合并为一个迭代器,如果某些可迭代对象长度不同,使用fillvalue填充。

    Args:
        *args: 可迭代对象的可变数量参数。
        fillvalue: 当某些可迭代对象长度不同时的填充值。

    Returns:
        zip_longest对象,迭代器。

    """
    iters = [iter(it) for it in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                iters.remove(it)
                if not iters:
                    return
                result.append(fillvalue)
        yield tuple(result)

# JSON描述