Custom zip_longest Implementation in Python

  • Share this:

Code introduction


This function implements the functionality of the zip_longest function in the itertools library. If the input lists have different lengths, it uses fillvalue to fill the shorter lists until all lists have the same length.


Technology Stack : itertools, collections.deque, collections.Counter

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    # 将可变数量的参数列表压缩成一个列表,如果最短的列表先遍历完,其他列表还有剩余值,则用fillvalue填充
    from itertools import zip_longest
    from collections import deque
    from collections import Counter

    def fill_deques(deques, fillvalue):
        for deque_ in deques:
            while len(deque_) < max(len(dq) for dq in deques):
                deque_.append(fillvalue)

    # 创建deque列表,每个deque对应一个参数列表
    deques = [deque(iter(lst)) for lst in args]
    # 根据参数列表的长度填充deque
    fill_deques(deques, fillvalue)
    # 使用zip_longest迭代deque,如果某个deque遍历完,则用fillvalue填充
    return [deque_.popleft() for deque_ in deques]