Combining Iterables with Fillvalue

  • Share this:

Code introduction


Combine multiple iterable objects into a list of tuples, if an iterable object runs out of elements prematurely, fillvalue is used to fill the remaining positions.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """将可迭代对象组合成元组列表,如果最短的迭代器耗尽,则使用fillvalue填充。

    Args:
        *args: 可变数量的可迭代对象。
        fillvalue: 当最短的迭代器耗尽时使用的填充值。

    Returns:
        一个列表,其中包含元组,每个元组包含来自每个迭代器的元素。
    """
    from itertools import zip_longest
    return list(zip_longest(*args, fillvalue=fillvalue))                
              
Tags: