Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function takes any number of iterable objects as arguments and combines them into tuples. If the length of these iterables is inconsistent, the shorter tuples are filled with the specified fillvalue.


Technology Stack : Built-in functions zip(), iterators

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """像zip()函数一样,将传入的可迭代对象组合成元组,如果可迭代对象长度不一致,则以fillvalue填充较短的元组。

    Args:
        *args: 可变数量的可迭代对象。
        fillvalue: 当可迭代对象长度不一致时用于填充的值。

    Returns:
        一个迭代器,返回由元组组成的列表。
    """
    iterators = [iter(arg) for arg in args]
    while True:
        result = []
        for iterator in iterators:
            try:
                result.append(next(iterator))
            except StopIteration:
                result.append(fillvalue)
        if len(set(len(x) for x in result)) == 1:
            break
    return result