Combining Iterators with Fillvalue using zip_longest

  • Share this:

Code introduction


This function combines multiple iterators into a single iterator, where each element is a tuple from each input iterator. If one of the iterators runs out, the corresponding tuple in the result will contain the `fillvalue`.


Technology Stack : zip_longest (built-in function)

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 这个函数会返回一个迭代器,其中每个元素是来自每个输入迭代器的元素的一个元组。如果其中一个迭代器耗尽,那么结果中的相应元组将包含 `fillvalue`。

    # 代码所属类型: 函数
    # 代码难度: 中级
    # 代码含义解释: 该函数用于将多个迭代器组合成一个新的迭代器,如果迭代器长度不一致,则使用fillvalue填充。
    # 代码所使用到的包和技术栈: zip_longest (内置函数)

    # 代码含义解释: This function combines multiple iterators into a single iterator, where each element is a tuple from each input iterator. If one of the iterators runs out, the corresponding tuple in the result will contain the `fillvalue`.

    # 代码所使用到的包和技术栈: zip_longest (built-in function)

    from itertools import zip_longest

    for tup in zip_longest(*iterables, fillvalue=fillvalue):
        yield tup

# 示例使用
iter1 = [1, 2, 3]
iter2 = ['a', 'b']
iter3 = [True, False]

result = list(zip_longest(iter1, iter2, iter3, fillvalue='X'))
print(result)  # 输出: [(1, 'a', True), (2, 'b', False), (3, 'X', None)]