Combining Iterables with FillValue

  • Share this:

Code introduction


This function combines multiple iterable objects into an iterator. If an iterable object is shorter than the others, it fills the remaining positions with fillvalue


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 这个函数将多个可迭代对象组合成一个迭代器,其中较短的迭代器用fillvalue填充
    from itertools import zip_longest
    from collections import deque

    def fill_values(fill_values, it):
        for item in it:
            fill_values.append(item)

    fill_values = deque()
    for iterable in iterables:
        fill_values.append(fillvalue)
        fill_values.extend(iterable)

    return zip_longest(fill_values, *iterables)