是否有一个内置函数,其工作方式类似于 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}