Combining Iterables with Fillvalue

  • Share this:

Code introduction


The zip_longest function takes any number of iterable arguments and combines them into a new list. If one of the lists is shorter than the others, the missing parts are filled with a value specified by fillvalue.


Technology Stack : Built-in library

Code Type : Built-in functions

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    # 将可变数量的参数列表组合成一个新的列表,如果某个列表较短,则用fillvalue填充
    def _next(items):
        for item in items:
            while hasattr(item, '__next__'):
                yield next(item)
            yield fillvalue

    iterators = [iter(lst) for lst in args]
    while True:
        yield tuple(_next(iterators))