Custom zip_longest Implementation

  • Share this:

Code introduction


This custom function implements the functionality of the zip_longest function from the itertools library, which combines iterable objects. If the lengths of the iterable objects are inconsistent, it uses fillvalue to fill


Technology Stack : itertools

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    # 使用内置库itertools中的zip_longest函数实现长序列的zip操作
    from itertools import zip_longest

    def next_item(enumerate_args):
        for it in enumerate_args:
            if not it[1]:
                yield fillvalue
            else:
                yield next(it[1])

    # 创建一个生成器,每次调用时返回zip_longest的一个元素
    def iterator():
        while True:
            yield next_item(args)

    # 创建一个迭代器,使用迭代器生成zip_longest的结果
    return iterator()                
              
Tags: