Combining Variable-Length Sequences with Fillvalue

  • Share this:

Code introduction


Create an iterator that combines variable-length sequences into tuples, and fills with the specified fill value if the sequence lengths are different.


Technology Stack : Built-in library

Code Type : Built-in library functions

Code Difficulty :


                
                    
def zip_longest(*args, fillvalue=()):
    """对可变长度的序列进行组合,如果长度不同,用fillvalue填充。

    Args:
        *args: 可变数量的序列。
        fillvalue: 当序列长度不同时的填充值。

    Returns:
        一个迭代器,包含组合后的元组,如果序列长度不同,则用fillvalue填充。

    Example:
        >>> list(zip_longest([1, 2, 3], ['a', 'b'], fillvalue='x'))
        [(1, 'a'), (2, 'b'), (3, 'x')]

    """
    args = [iter(arg) for arg in args]
    while True:
        yield tuple(next(arg, fillvalue) for arg in args)

# JSON描述