sta*_*ser 3 python dictionary list list-manipulation
我有两个字典,如下所述,我需要将字典列表中的每个元素与其他字典列表中的相应元素相乘并打印结果。我已经成功地增加了一个列表,如何使其动态化?
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]) )
Run Code Online (Sandbox Code Playgroud)
您可以将每个列表压缩在一起并使用如下所示的字典理解:
result = {i :[x*y for x, y in zip(dict1[i], dict2[i])] for i in dict1.keys()}
Run Code Online (Sandbox Code Playgroud)
这假设 dict1 和 dict2 共享相同的密钥