Python将列表列表映射到字典

2024-05-17 06:22:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个列表和一个词汇表联系起来。 一方面,我有以下清单:

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_1中的每个单词都被映射到字典dict中的每个值,而且,请注意,在dict中找不到的'am'中的'am'取了值[0,0,0]。你知道吗

谢谢你的帮助。你知道吗


Tags: 词汇表hello列表new字典addressamjohn
2条回答

只需使用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]]]
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=[[dict[x] for x in l if x in dict] for l in list_1]

如果您想要一个列表,即使dict中不存在该键

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

相关问题 更多 >