Merging Iterables with Fillvalue: zip_longest Function

  • Share this:

Code introduction


The function merges multiple iterable objects into an iterator. If some iterable objects have different lengths, it fills them with a specified fillvalue.


Technology Stack : Built-in iterators, for loops, try-except statements

Code Type : Function

Code Difficulty : Intermediate


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

    Args:
        *args: 可变数量的可迭代对象。
        fillvalue: 当最长的可迭代对象结束时,较短的可迭代对象会用此值填充。

    Returns:
        zip_longest对象,它是一个迭代器,可以像zip对象一样迭代。

    """
    iterators = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == len(args):
            break
    return result