Combining Iterables with zip_longest

  • Share this:

Code introduction


Combine multiple iterable objects into a list of tuples using the zip_longest function from the itertools module, if an iterable object is shorter, fill it with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """将多个可迭代对象组合成元组列表,如果某个可迭代对象较短,则使用fillvalue填充。
    
    Args:
        *args: 可迭代对象列表。
        fillvalue: 当某个可迭代对象较短时,用于填充的值,默认为()。

    Returns:
        一个元组列表,每个元组包含来自不同可迭代对象的元素,如果某个可迭代对象较短,则使用fillvalue填充。
    """
    from itertools import zip_longest
    return list(zip_longest(*args, fillvalue=fillvalue))                
              
Tags: