类似于zip()的内置函数,使用无值从左开始填充不相等的长度 [英] zip()-like built-in function filling unequal lengths from left with None value

查看:58
本文介绍了类似于zip()的内置函数,使用无值从左开始填充不相等的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个内置函数,其功能类似于zip(),但会填充结果,以便结果列表的长度为最长输入的长度,并从左侧起填充与例如没有

Is there a built-in function that works like zip(), but fills the results so that the length of the resulting list is the length of the longest input and fills the list from the left with e.g. None?

已经有一个 answer 使用 zip_longest itertools 模块和相应的问题与此非常相似。但是使用 zip_longest 似乎只能填充右边的缺失数据。

There is already an answer using zip_longest from itertools module and the corresponding question is very similar to this. But with zip_longest it seems that you can only fill missing data from the right.

这里可能是一个用例为此,假设我们仅以这样的方式存储名称(仅是示例):

Here might be a use case for that, assuming we have names stored only like this (it's just an example):

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

没有其他排列方式,例如( [ Poppins, Mary] [ Poppins, Dr, Mary] )等等。

There is no other permutation like (["Poppins", "Mary"], ["Poppins", "Dr", "Mary"]) and so on.

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

How can I get results like this using built-in functions?

>>> 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}


推荐答案

使用 zip_longest ,但使用反向列表。

Use zip_longest but reverse lists.

示例

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}

这篇关于类似于zip()的内置函数,使用无值从左开始填充不相等的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆