类似 zip() 的内置函数用 None 值从左侧填充不等长度

2024-05-23

是否有一个内置函数,其工作方式类似于 zip(),但填充结果,以便结果列表的长度是最长输入的长度并填充列表从左边例如None?

已经有一个answer https://stackoverflow.com/a/1277311/2648551 using 最长的拉链 https://docs.python.org/3/library/itertools.html#itertools.zip_longest from itertools模块和相应的question https://stackoverflow.com/q/1277278/2648551与此非常相似。但与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}

Use zip_longest但反向列表。

Example:

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}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类似 zip() 的内置函数用 None 值从左侧填充不等长度 的相关文章