Iterative Tuple Packing with FillValue

  • Share this:

Code introduction


The function is used to pack elements from multiple iterable objects into tuples and return an iterator. If an iterable is exhausted, fillvalue is used to fill the remaining tuples.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    从最短的序列开始,将可迭代对象中的元素打包成元组,并返回一个迭代器。
    如果有可迭代对象耗尽,则使用fillvalue填充。
    """
    # 使用内置的itertools库中的zip_longest函数实现
    from itertools import zip_longest

    # 返回zip_longest函数的结果
    return zip_longest(*iterables, fillvalue=fillvalue)                
              
Tags: