Zip Longest Function for Merging Iterables with Fillvalue

  • Share this:

Code introduction


This function uses `itertools.zip_longest` to merge elements from multiple iterable objects into an iterator. If an iterable object has been exhausted, it uses `fillvalue` to fill in the missing values.


Technology Stack : itertools, collections, typing

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import deque
    from typing import Any, Iterable, Iterator, List

    # 生成一个无限迭代器,每次迭代从每个可迭代对象中获取一个元素
    def interleave(*iterables):
        iterators = [iter(it) for it in iterables]
        while True:
            for i, it in enumerate(iterators):
                try:
                    yield next(it)
                except StopIteration:
                    iterators[i] = iter([fillvalue])
    
    # 使用zip_longest将无限迭代器转换为一个有限迭代器
    return iter((i for i in interleave(*args) if i is not fillvalue))