Combining Variable-Length Iterables with Fillvalue

  • Share this:

Code introduction


This function combines multiple iterable objects of variable lengths into tuples. If an iterable object is shorter than the others, it is filled with fillvalue


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    # 将可变数量的输入参数组合成元组,如果某个参数长度短于其他参数,则使用fillvalue填充
    # 使用itertools.zip_longest实现,zip_longest是itertools库的一部分

    from itertools import zip_longest

    def generate_tuples():
        return zip_longest(*args, fillvalue=fillvalue)

    return generate_tuples()                
              
Tags: