Extended Zip Function with Fillvalue

  • Share this:

Code introduction


This function is similar to the zip() function, but when the shortest iterable is exhausted, the others continue to be filled with fillvalue.


Technology Stack : itertools.zip_longest, collections.deque

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Like zip(), but the iterator(s) are extended with fillvalues if the shortest iterable is exhausted.
    """
    # 使用内置的zip函数和itertools.zip_longest来合并多个可迭代对象
    from itertools import zip_longest
    from collections import deque

    # 创建一个deque来存储每个可迭代对象中的元素,以便可以重复使用
    iterators = [deque(iterable) for iterable in iterables]
    while iterators:
        # 创建一个元组,其中包含从每个可迭代对象中取出的元素
        result = [iterators[i].popleft() for i in range(len(iterators))]
        # 如果某个可迭代对象已耗尽,则用fillvalue填充
        if not all(iterators):
            result = [fillvalue if not it else it.popleft() for it in iterators]
        yield result