Creating an Iterator with Zip_longest in Python

  • Share this:

Code introduction


This function creates an iterator that yields tuples, each containing elements from each of the input iterable objects. If an iterable object runs out of elements, a specified fill value is used.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """接受多个可迭代对象作为输入,返回一个迭代器,该迭代器会返回元组,每个元组包含来自每个输入可迭代对象的元素。
    如果某个可迭代对象耗尽,则使用`fillvalue`填充。
    """
    from itertools import zip_longest
    from collections import deque

    # 创建一个deque,初始化为空,用于存储可迭代对象中的元素
    buffer = deque()
    for iterable in iterables:
        buffer.extend(iterable)
    # 使用zip_longest处理可迭代对象,并使用buffer中的元素填充耗尽的可迭代对象
    return zip_longest(buffer, fillvalue=fillvalue)

# 代码示例使用
if __name__ == "__main__":
    list1 = [1, 2, 3, 4]
    list2 = ['a', 'b', 'c']
    list3 = [True, False, True]

    # 使用zip_longest处理三个列表,当某个列表耗尽时,用None填充
    result = list(zip_longest(list1, list2, list3, fillvalue=None))
    print(result)