加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – zip() – 类似于内置函数,从左边填充不等长,无值

发布时间:2020-12-20 12:35:19 所属栏目:Python 来源:网络整理
导读:是否有类似zip()的内置函数,但填充结果,以便结果列表的长度是最长输入的长度,并从左侧填充列表,例如没有? 已经有一个answer使用来自itertools模块的zip_longest,相应的question与此非常相似.但是使用zip_longest,您似乎只能从右侧填充缺失的数据. 这可能是
是否有类似zip()的内置函数,但填充结果,以便结果列表的长度是最长输入的长度,并从左侧填充列表,例如没有?

已经有一个answer使用来自itertools模块的zip_longest,相应的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}

解决方法

使用zip_longest但反向列表.

例:

from itertools import zip_longest

header = ["title","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.','firstname': 'Joe'}
>>> dict(zip_longest(reversed(header),reversed(person_2)))
{'lastname': 'Poppins','title': None} 
>>> dict(zip_longest(reversed(header),reversed(person_3))) 
{'lastname': 'Smith','firstname': None,'title': None}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读