Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function is used to combine multiple iterable objects according to the length of the longest object. If an iterable object is shorter, it will be filled with fillvalue.


Technology Stack : Built-in function

Code Type : Function

Code Difficulty : Advanced


                
                    
def zip_longest(*args, fillvalue=None):
    """Zip the input iterables (elements of args) together into a single iterable of tuples.
    The iterator stops when the shortest input iterable is exhausted, unless the 'fillvalue'
    parameter is set, in which case missing values are filled in with this value.

    Args:
        *args: Variable length argument list. An arbitrary number of iterables.
        fillvalue: The value to use for missing values in the shorter iterables.

    Returns:
        An iterator of tuples.

    Example:
        >>> list(zip_longest([1, 2, 3], [4, 5], [6], fillvalue=0))
        [(1, 4, 6), (2, 5, 0), (3, 0, 0)]

    Type:
        函数

    Hard:
        中级

    Explain:
        该函数用于将多个可迭代对象按长度最长的对象进行组合,如果某个可迭代对象较短,则用fillvalue填充。

    Tech:
        内置函数

    Explain_en:
        This function is used to combine multiple iterable objects according to the length of the longest object. If an iterable object is shorter, it will be filled with fillvalue.

    Tech_en:
        Built-in function
    """
    from itertools import zip_longest
    return zip_longest(*args, fillvalue=fillvalue)