Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-将列表映射到字典_Python_List_Dictionary - Fatal编程技术网

Python-将列表映射到字典

Python-将列表映射到字典,python,list,dictionary,Python,List,Dictionary,我想在列表列表和列表词汇之间建立一个关联。 一方面,我有以下清单: list_1=[['new','address'],['hello'],['I','am','John']] 另一方面,我有一本列表词典: dict={'new':[1,3,4], 'address':[0,1,2], 'hello':[7,8,9], 'I':[1,1,1], 'John':[1,3,4]} 我想要的是一个新的列表,如下所示: list_2=[[[1,3,4],[0,1,2]],[[7,8,9]],[[1,

我想在列表列表和列表词汇之间建立一个关联。 一方面,我有以下清单:

list_1=[['new','address'],['hello'],['I','am','John']]
另一方面,我有一本列表词典:

dict={'new':[1,3,4], 'address':[0,1,2], 'hello':[7,8,9], 'I':[1,1,1], 'John':[1,3,4]}
我想要的是一个新的列表,如下所示:

list_2=[[[1,3,4],[0,1,2]],[[7,8,9]],[[1,1,1],[0,0,0],[1,3,4]]]
这意味着
list\u 1
中的每个单词都映射到字典
dict
中的每个值,而且,请注意
list\u 1
中未在
dict
中找到的
'am'
取值
[0,0,0]


Thanx提前获取帮助。

只需使用dict.get使用字典查询重新生成列表,如果找不到键,则使用默认值:

list_1=[['new','address'],['hello'],['I','am','John']]

d={'new':[1,3,4], 'address':[0,1,2], 'hello':[7,8,9], 'I':[1,1,1], 'John':[1,3,4]}

list_2=[[d.get(k,[0,0,0]) for k in sl] for sl in list_1]

print(list_2)
结果:

[[[1, 3, 4], [0, 1, 2]], [[7, 8, 9]], [[1, 1, 1], [0, 0, 0], [1, 3, 4]]]
如果您想要一个列表,即使dict中不存在该键

list_2=[[dict.get(x, []) for x in l] for l in list_1]
list_2=[[dict.get(x, []) for x in l] for l in list_1]