我有两个字典,如下所述,我需要将字典列表中的每个元素与其他字典列表中的相应元素相乘并打印结果。我已经成功地增加了一个列表,如何使其动态化?
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]) )
最佳答案
您可以将每个列表压缩在一起并使用像这样的字典理解:
result = {i :[x*y for x, y in zip(dict1[i], dict2[i])] for i in dict1.keys()}
假设 dict1 和 dict2 共享相同的键
关于python - 如何将字典中的列表元素相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53078068/