Aggregating Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


This function uses the zip_longest function from the itertools library to aggregate elements from multiple iterable objects into an iterator. When the shortest iterable is exhausted, the remaining iterators are filled with a fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    Returns an iterator that aggregates elements from each of the iterables.
    The iterator returns pairs, where the first item in each pair is from the
    first iterable, and the second item is from the second iterable, and so on.
    The iterator stops when the shortest iterable is exhausted, after which
    each subsequent element yields a fillvalue.
    """
    # 使用itertools库中的zip_longest函数
    from itertools import zip_longest

    # 迭代并返回结果
    return zip_longest(*args, fillvalue=fillvalue)                
              
Tags: