Combining Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


The zip_longest function can take multiple iterable objects and combine them together. If an iterable object runs out of elements, it is filled with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # zip_longest 是 itertools 模块中的一个函数,用于将多个可迭代对象合并在一起,如果某个可迭代对象中的元素用完,
    # 则使用 fillvalue 填充。

    def _all_equal(len_list):
        return all(len(iterable) == len_list[0] for iterable in len_list)

    iters = [iter(iterable) for iterable in iterables]
    while True:
        len_list = [len(list(it)) for it in iters]
        if not _all_equal(len_list):
            iters = [it for it in iters if it]
            if not iters:
                break
            yield [next(it, fillvalue) for it in iters]

        for it in iters:
            next(it)

                        
              
Tags: