Combining Lists with Fillvalue

  • Share this:

Code introduction


Combine multiple lists into a new list, and fill the shorter lists with a specified fill value if necessary.


Technology Stack : Combine multiple lists into a new list, and fill the shorter lists with a specified fill value if necessary.

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    # 将可变数量的列表组合成一个列表,如果某个列表较短,则用fillvalue填充
    def _nextit():
        for it in args:
            for elem in it:
                yield elem

    it = _nextit()
    result = []
    while True:
        try:
            result.append(next(it))
        except StopIteration:
            break
    return result