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} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- python – Django Rest-Framework嵌套序列化器命令
- django – Rest Framework教程IntegrityError创建片段
- python如何压缩新文件到已有ZIP文件
- python – 我想将gevent.evnet用于celery.task
- python – 使用thread.join确保所有线程都已连接时的Pydev
- django – 使用模型表单创建自定义错误消息
- python – 有没有人知道正则表达式来验证MSISDN格式的手机
- Python – 如何让客户端能够连接多次?
- python根据时间获取周数代码实例
- 基于Python对象引用、可变性和垃圾回收详解