代码之家  ›  专栏  ›  技术社区  ›  colidyre

类似于zip()的内置函数,用无值填充从左到右不等的长度

  •  3
  • colidyre  · 技术社区  · 8 年前

    从左边 例如。 None

    已经有一个 answer 使用 zip_longest itertools 模块和相应的 question 与此非常相似。但是 zip_longest

    这里可能有一个这样的用例,假设我们只有这样存储的名称(这只是一个例子):

    header = ["title", "firstname", "lastname"]
    person_1 = ["Dr.", "Joe", "Doe"]
    person_2 = ["Mary", "Poppins"]
    person_3 = ["Smith"]
    

    没有其他排列像( ["Poppins", "Mary"] ["Poppins", "Dr", "Mary"] )等等。

    如何使用内置函数获得这样的结果?

    >>> dict(magic_zip(header, person_1))
    {'title': 'Dr.', 'lastname': 'Doe', 'firstname': 'Joe'}
    >>> dict(magic_zip(header, person_2))
    {'title': None, 'lastname': 'Poppins', 'firstname': 'Mary'}
    >>> dict(magic_zip(header, person_3))
    {'title': None, 'lastname': 'Smith', 'firstname': None}
    
    4 回复  |  直到 8 年前
        1
  •  6
  •   Austin    8 年前

    使用 zip_longest

    例子 :

    from itertools import zip_longest
    
    header = ["title", "firstname", "lastname"]
    person_1 = ["Dr.", "Joe", "Doe"]
    person_2 = ["Mary", "Poppins"]
    person_3 = ["Smith"]
    
    print(dict(zip_longest(reversed(header), reversed(person_2))))
    # {'lastname': 'Poppins', 'firstname': 'Mary', 'title': None}
    

    >>> dict(zip_longest(reversed(header), reversed(person_1))) 
    {'title': 'Dr.', 'lastname': 'Doe', 'firstname': 'Joe'}
    >>> dict(zip_longest(reversed(header), reversed(person_2)))
    {'lastname': 'Poppins', 'firstname': 'Mary', 'title': None} 
    >>> dict(zip_longest(reversed(header), reversed(person_3))) 
    {'lastname': 'Smith', 'firstname': None, 'title': None}
    
        2
  •  5
  •   DSM    8 年前

    简单使用 zip_longest 并以相反的方向读取参数:

    In [20]: dict(zip_longest(header[::-1], person_1[::-1]))
    Out[20]: {'lastname': 'Doe', 'firstname': 'Joe', 'title': 'Dr.'}
    
    In [21]: dict(zip_longest(header[::-1], person_2[::-1]))
    Out[21]: {'lastname': 'Poppins', 'firstname': 'Mary', 'title': None}
    
    In [22]: dict(zip_longest(header[::-1], person_3[::-1]))
    Out[22]: {'lastname': 'Smith', 'firstname': None, 'title': None}
    

    由于zip*函数需要能够处理一般的iterable,因此它们不支持“从左开始”填充,因为您需要首先耗尽iterable。在这里我们可以自己翻转东西。

        3
  •  2
  •   Jean-François Fabre    8 年前

    import itertools
    
    def magic_zip(*args):
        return itertools.zip_longest(*map(reversed,args))
    

    测试(当然,在dict构建的情况下,只需要2个参数):

    for p in (person_1,person_2,person_3):
        print(dict(magic_zip(header,p)))
    

    结果:

    {'lastname': 'Doe', 'title': 'Dr.', 'firstname': 'Joe'}
    {'lastname': 'Poppins', 'title': None, 'firstname': 'Mary'}
    {'lastname': 'Smith', 'title': None, 'firstname': None}
    
        4
  •  1
  •   blhsing    8 年前
    def magic_zip(*lists):
        max_len = max(map(len, lists))
        return zip(*([None] * (max_len - len(l)) + l for l in lists))
    
    推荐文章