Combining Iterables with Fillvalue

  • Share this:

Code introduction


The function combines multiple iterable objects into an iterator. If one of the iterable objects is traversed out, fillvalue is used to fill in.


Technology Stack : zip, traversal

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 将多个可迭代对象组合成一个迭代器,如果其中某个可迭代对象先遍历完,则使用fillvalue填充
    zipped = zip(*iterables)
    while True:
        yield zipped
        for i, iterable in enumerate(iterables):
            if len(iterable) > len(zipped[i]):
                break
        else:
            break                
              
Tags: