python - 如何从两个嵌套列表中制作字典?
问题描述
我有两个嵌套列表:
list1 = [['s0'], ['s1'], ['s2']]
list2 = [['hello','world','the'],['as','per','the'],['assets','order']]
我想从这些列表中创建一个字典,其中的键list1
和值来自list2
:
d = {s0:['hello','world','the'],s1:['as','per','the'],s2:['assets','order']}
输出应如下所示:
d = {s0:['hello','world','the'],s1:['as','per','the'],s2:['assets','order']}
list1
如果是普通(非嵌套)列表,则以下代码有效。list1
但是当是嵌套列表时它不起作用。
dict(zip(list1, list2))
解决方案
这里的问题是列表不是可散列的,因此您可以做的一件事是使用当前方法将字符串(不可itertools.chain
变)作为键构建字典(阅读此处以获取更详细的说明)关于这个话题):
from itertools import chain
dict(zip(chain.from_iterable(list1),list2))
{'s0': ['hello', 'world', 'the'],
's1': ['as', 'per', 'the'],
's2': ['assets', 'order']}
推荐阅读
- automation - 编码的 ui 对象存储库
- mysql - 表被锁定在 MySQL 数据库中
- mongodb - Mongodb 3.4.7 分组后一个字段的聚合不同计数
- c# - C# 检查 PropertyInfo 的类型是否是原始的
- android - ExoPlayer ConcatenatingMediaSource ArrayIndexOutOfBoundsException
- matlab - 如何在matlab中对结构数组求和?
- magento - 我在 magento 2 的前端创建了一个自定义菜单
- html - 转到 chrome 移动设备视图时出现奇怪的 css/html 间隙
- ios - ARKit Ball Pass through Torus 孔碰撞检测
- kubernetes - 错误:服务器没有资源类型“svc”