Combining Iterables with FillValue

  • Share this:

Code introduction


Combine multiple iterable objects into tuples, filling the shorter ones with fillvalue if necessary


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 将可迭代对象组合为元组,如果某个可迭代对象已经遍历完成,则用fillvalue填充
    zipped = zip(*iterables)
    for i in iterables:
        while len(i) < len(zipped[0]):
            i = i + (fillvalue,)
    return zipped

# JSON 格式输出