Combining Variable-Length Lists with Fillvalue

  • Share this:

Code introduction


This function combines lists of variable lengths into a list of tuples. If an element count in a list is less than the others, it fills with fillvalue. It uses the zip_longest function from itertools, deque from collections, and functions from operator and functools for auxiliary processing.


Technology Stack : itertools, collections, operator, functools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest as it_zip_longest
    from collections import deque
    from operator import itemgetter
    from functools import reduce

    def make_deque(obj):
        if isinstance(obj, list):
            return deque(obj)
        elif isinstance(obj, deque):
            return obj
        else:
            return deque([obj])

    def get_max_length(args):
        return max(map(len, args))

    def flatten_list(obj):
        return [item for sublist in obj for item in sublist]

    def check_and_fill(args, max_length):
        for i in range(len(args)):
            if len(args[i]) < max_length:
                args[i] += [fillvalue] * (max_length - len(args[i]))
        return args

    max_length = get_max_length(args)
    args = check_and_fill(args, max_length)
    args = [make_deque(arg) for arg in args]
    args = flatten_list(args)
    return list(map(list, it_zip_longest(*args)))