Combining Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


This function uses itertools library's zip_longest to combine multiple iterable objects. If an iterable object has fewer elements, it fills with a specified fillvalue. If the combined elements are of different lengths, collections library's deque is used to maintain consistent length.


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

    # 使用zip_longest来组合多个可迭代对象,如果某个可迭代对象中的元素不足,则用fillvalue填充
    combined = zip_longest(*args, fillvalue=fillvalue)

    # 将组合后的结果转换为列表,并确保每个元素都是相同的长度
    result = [list(pair) for pair in combined]
    
    # 如果有元素不足,则使用deque来保持长度一致
    for i, item in enumerate(result):
        if len(item) < len(args):
            result[i] = deque(item + [fillvalue] * (len(args) - len(item)))
    
    return result