Combining Iterables with FillValue using zip_longest

  • Share this:

Code introduction


The function combines multiple iterable objects into a new iterator. If an iterable is exhausted, a specified value is used to fill in, suitable for handling iterables of different lengths.


Technology Stack : code, itertools.zip_longest, recursive function

Code Type : Function

Code Difficulty :


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 将多个可迭代对象组合成一个新的迭代器,如果某个可迭代对象耗尽,则使用fillvalue填充
    # 使用了内置的zip_longest函数,这个函数在Python的itertools模块中

    from itertools import zip_longest

    def recursive_zip_longest(*iterables, fillvalue=None):
        # 递归函数,用于处理嵌套的可迭代对象
        iters = [iter(i) for i in iterables]
        while True:
            try:
                # 尝试从每个可迭代对象中获取一个元素
                result = [next(i, fillvalue) for i in iters]
            except StopIteration:
                # 如果有可迭代对象耗尽,则使用fillvalue填充剩余的元素
                result = [fillvalue] * len(iterables)
                break
            yield result

    return recursive_zip_longest(*iterables, fillvalue=fillvalue)