Merging Iterables with Fillvalue

  • Share this:

Code introduction


This function is used to merge multiple iterable objects into an iterator. If the iterable objects are of different lengths, fillvalue is used to fill the shorter iterable objects.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


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

    def fill_deque(deq, fill_value):
        while len(deq) < max(map(len, args)):
            deq.appendleft(fill_value)

    # 创建一个队列,用于填充缺失的值
    deq = deque()
    fill_deque(deq, fillvalue)

    # 使用zip_longest来合并列表,如果某个列表较短,则用fillvalue填充
    result = zip_longest(*args)
    return list(result)