Implementing zip_longest with itertools

  • Share this:

Code introduction


This function takes any number of iterable objects as arguments and returns an iterator that produces tuples, each containing elements from each iterable. If an iterable runs out of elements, missing values are filled with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    # 这个函数使用 itertools 库中的 zip_longest 方法来合并多个可迭代对象,如果最长的可迭代对象被用完,那么较短的可迭代对象将用 fillvalue 填充。
    
    import itertools
    
    def my_zip_longest(*args, fillvalue=None):
        # 使用 itertools.zip_longest 来实现功能
        return itertools.zip_longest(*args, fillvalue=fillvalue)
    
    return my_zip_longest                
              
Tags: