Merging Iterables with Fillvalue using zip_longest

  • Share this:

Code introduction


This function merges multiple iterable objects. If an iterable object does not have enough elements, it fills the missing values with a specified fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    zip_longest(*iterables, fillvalue=None)
    """
    将多个可迭代对象合并,如果某个可迭代对象中元素不足,则用fillvalue填充。

    :param *iterables: 任意数量的可迭代对象
    :param fillvalue: 缺失值填充,默认为None
    :return: 合并后的迭代器
    """
    # 使用itertools.zip_longest实现功能
    from itertools import zip_longest
    return zip_longest(*iterables, fillvalue=fillvalue)                
              
Tags: