Zip Longest Function: Merging Iterables with Fillvalue

  • Share this:

Code introduction


Defined a function zip_longest that merges multiple iterable objects into a tuple sequence. If an iterable is not long enough, fillvalue is used to fill it.


Technology Stack : Built-in library itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # 从内置库itertools中选取zip_longest函数
    # 功能:将多个可迭代对象合并成一个元组序列,如果某个可迭代对象长度不足,则用fillvalue填充

    def _all_iterable_empty(iterables):
        for iterable in iterables:
            if iterable:
                return False
        return True

    num_iterables = len(iterables)
    for i in count():
        if _all_iterable_empty(iterables):
            return
        for j in range(num_iterables):
            if i >= len(iterables[j]):
                yield (fillvalue,) * num_iterables
                return
            yield tuple(iterables[k][i] for k in range(num_iterables))

# JSON格式的代码描述