Implementing zip_longest Functionality

  • Share this:

Code introduction


This function aggregates elements from multiple iterable objects into an iterator. It stops when the shortest input iterable is exhausted and fills the rest with the fillvalue if longer iterables still have elements left.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """
    Returns an iterator that aggregates elements from each of the iterables.
    The iterator stops when the shortest iterable is exhausted, filling with fillvalue if longer iterables still have elements left.
    """
    # 使用 itertools.zip_longest 来实现功能
    from itertools import zip_longest

    return zip_longest(*args, fillvalue=())                
              
Tags: