Merging Iterables with FillValue Using Zip_longest

  • Share this:

Code introduction


This function merges multiple iterable objects into an iterator, if one iterable object is traversed first, it uses fillvalue to fill in, and returns the merged result list.


Technology Stack : itertools.zip_longest, collections.deque

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 将多个可迭代对象合并为一个迭代器,如果其中一个可迭代对象先遍历完成,则使用fillvalue填充
    from itertools import zip_longest
    from collections import deque

    # 将所有可迭代对象转换为队列
    queues = [deque(iterable) for iterable in iterables]
    # 初始化结果列表
    result = []

    # 遍历队列,直到所有队列都为空
    while queues:
        # 获取当前所有队列的第一个元素
        current_values = [queue.popleft() if queue else fillvalue for queue in queues]
        # 将当前值添加到结果列表
        result.append(current_values)

    return result