Custom Zip Longest Function Using Built-in Libraries

  • Share this:

Code introduction


This function implements a functionality similar to zip_longest but using built-in libraries. It combines multiple iterable objects into an iterator, using fillvalue if one of the iterables is exhausted.


Technology Stack : collections.deque, itertools.zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import deque

    # 将所有输入的迭代器转换为deque,这样可以动态地添加元素
    iters = [deque(iter(args[i])) for i in range(len(args))]
    while True:
        # 从每个迭代器中获取一个元素,如果迭代器已耗尽,则使用fillvalue填充
        result = [iterable[0] if iterable else fillvalue for iterable in iters]
        yield tuple(result)
        # 移除已经返回的元素
        for iterable in iters:
            if iterable:
                iterable.popleft()
            else:
                # 如果所有迭代器都已耗尽,则退出循环
                return