Python 如何在字典中增加列表元素

Python 如何在字典中增加列表元素,python,list,dictionary,list-manipulation,dictionary-comprehension,Python,List,Dictionary,List Manipulation,Dictionary Comprehension,我有两个字典,如下所述,我需要将字典列表中的每个元素与其他字典列表中的相应元素相乘,然后打印结果。我已经成功地将一个列表相乘,如何使其动态化 dict1 = {0: [1, 1, 0, 1, 1, 0], 1: [1, 0, 1, 1, 1, 0]} dict2 = { 0: [16, 0, 2, 0, 0, 0], 1: [15, 0, 0, 0, 1, 0]} result = { 0: [16, 0, 0, 0, 0, 0], 1:[15, 0, 0, 0, 1, 0]} from

我有两个字典,如下所述,我需要将字典列表中的每个元素与其他字典列表中的相应元素相乘,然后打印结果。我已经成功地将一个列表相乘,如何使其动态化

dict1 = {0: [1, 1, 0, 1, 1, 0], 1: [1, 0, 1, 1, 1, 0]}

dict2 = { 0: [16, 0, 2, 0, 0, 0], 1: [15, 0, 0, 0, 1, 0]}

result = { 0: [16, 0, 0, 0, 0, 0], 1:[15, 0, 0, 0, 1, 0]}

from operator import mul
result = list( map(mul, dict1[0], dict2[0]) )

您可以将每个列表压缩在一起,并使用如下的dict理解:

result = {i :[x*y for x, y in zip(dict1[i], dict2[i])] for i in dict1.keys()}
这假设dict1和dict2共享相同的密钥

欢迎堆栈用户

你可以用听写理解来做这件事。不需要拉链

from operator import mul

dict1 = {0: [1, 1, 0, 1, 1, 0], 1: [1, 0, 1, 1, 1, 0]}
dict2 = {0: [16, 0, 2, 0, 0, 0], 1: [15, 0, 0, 0, 1, 0]}

result = {key: list(map(mul, dict1[key], dict2[key])) for key in dict1.keys() }

result
{0: [16, 0, 0, 0, 0, 0], 1: [15, 0, 0, 0, 1, 0]}
PEP 274——听写理解

它的内容类似于:对于键列表中的每个键,根据键和列表(map(mul,dict1[key],dict2[key])制作一个字典

希望有帮助