【问题标题】:How to Multiply list elements in dictionary如何将字典中的列表元素相乘
【发布时间】:2023-03-05 21:16:01
【问题描述】:

我有两个字典,如下所述,我需要将字典列表中的每个元素与其他字典列表中的相应元素相乘并打印结果。我设法将一个列表相乘,如何使其动态化?

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]) )

【问题讨论】:

    标签: python list dictionary list-manipulation


    【解决方案1】:

    欢迎栈用户,

    您可以使用 DICT COMPRHENSIONS 来做到这一点。不需要拉链。

    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 -- 字典理解 https://www.python.org/dev/peps/pep-0274/

    它的内容类似于:对于键列表中的每个键,从 key 和 list(map(mul, dict1[key], dict2[key])) 中创建一个字典

    希望有帮助

    【讨论】:

      【解决方案2】:

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

      result = {i :[x*y for x, y in zip(dict1[i], dict2[i])] for i in dict1.keys()}
      

      这假设 dict1 和 dict2 共享相同的键

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-06
        • 1970-01-01
        • 2012-01-01
        • 2021-08-14
        • 1970-01-01
        • 1970-01-01
        • 2021-08-11
        • 1970-01-01
        相关资源
        最近更新 更多