Python Zip Longest Equivalent with Fillvalue

  • Share this:

Code introduction


This function is used to pack multiple iterable objects into tuples, if the elements in an iterable object are insufficient, it uses fillvalue to fill.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    从a~z的顺序中,使用了内置的`zip_longest`函数,用于将可迭代对象打包成元组,如果某个可迭代对象中缺少元素,则使用fillvalue填充。
    """
    from itertools import zip_longest

    def next_item():
        for item in args:
            if len(item) > 0:
                yield item[0]
                item.pop(0)

    while True:
        try:
            yield tuple(next_item())
        except IndexError:
            break                
              
Tags: