Python#s Custom zip_longest Implementation

  • Share this:

Code introduction


This function takes multiple iterable objects as arguments and combines them into an iterator. If an iterable runs out, it is filled with fillvalue. Here, the zip_longest function from the itertools library is used.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 这个函数会返回一个迭代器,它将多个可迭代的对象组合起来,如果某个可迭代的对象耗尽了,就会用fillvalue填充。
    
    from itertools import zip_longest as zip_longest_itertools

    def xxx(arg1, arg2=None):
        # 使用 zip_longest 将两个列表组合,如果长度不等,则用 None 填充较短的列表
        return list(zip_longest_itertools(arg1, arg2, fillvalue=None))
    
    return xxx                
              
Tags: