Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function takes multiple iterable objects as arguments and combines them into a list of tuples. If the iterables are of unequal length, it fills in the missing parts with a fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    # 使用内置库itertools中的zip_longest函数来对齐不同长度的可迭代对象
    from itertools import zip_longest

    # 生成一个长列表,其中包含所有输入迭代器的元素,如果某个迭代器提前结束,则使用fillvalue填充
    zipped = zip_longest(*args, fillvalue=fillvalue)
    
    # 将zip对象转换为列表
    return list(zipped)                
              
Tags: