Python Function for Zipping Variable-Length Sequences with Fillvalue

  • Share this:

Code introduction


This function uses `itertools.zip_longest` to pack variable-length input sequences into tuples. If a sequence has been traversed completely, it uses `fillvalue` to fill in.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import deque

    def fill_deque(deq, fillvalue):
        while len(deq) < max(len(arg) for arg in args):
            deq.append(fillvalue)

    # 创建一个最大的迭代器长度
    max_length = max(len(arg) for arg in args)
    # 创建deque,用于填充
    deques = [deque() for _ in args]
    for arg in args:
        deques[len(arg)].extend(arg)

    fill_deque(deques, fillvalue)

    return zip_longest(*deques)