python - 如何将字典中的列表元素相乘

标签 python list dictionary 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]) )

最佳答案

您可以将每个列表压缩在一起并使用像这样的字典理解:

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/

相关文章:

python - 连接到另一个小部件的事件

python - Anaconda 和 Pycharm 有什么区别?

python - 将 CSV 的每一行存储为单独的列表/字典

python - 如何使用API​​将图像文件写入OpenERP的二进制字段

python - Pythonland 中的 Rubyist : what is a real world example of a tuple?

python - 如何按数字拆分列表列表?

python - 从列表中消除重复项的更快方法

list - 如何避免R中的循环:从列表中选择项目

c# - 打印字典值的简单方法?

python - 快速读取所有 csv 文件并更新共享字典