【问题标题】:Dot Product With One Dictionary Python带有一个字典 Python 的点积
【发布时间】:2021-04-30 23:13:15
【问题描述】:

我需要计算字典中两个键的点积。

res = {'Ben':['5', '0', '0', '0', '1', '4', '2'...], 
'Moose': ['5', '5', '0', '0', '0', '0', '3'...]}

我希望制作这样的东西。我想将 Ben 的值与 Moose 的值相乘。

Ans = 31 [5*5 + 0*5 + 0*0 + 0*0 + 1*0 + 4*0 + 2*3...]

我怎样才能用字典做到这一点?使用列表,我可以调用 np.dot 函数或编写一个小循环。

【问题讨论】:

    标签: python file dictionary dot-product


    【解决方案1】:

    您可以使用zip 并按如下方式一起遍历两个键:

    sum = 0
    for x, y in zip(res['Ben'], res['Moose']):
        sum += int(x) * int(y)
    print(sum)
    

    【讨论】:

      【解决方案2】:

      您可以在形成点积的列表推导上使用 sum

      res = {'Ben':['5', '0', '0', '0', '1', '4', '2'], 
      'Moose': ['5', '5', '0', '0', '0', '0', '3']}
      
      ans = sum(int(b) * int(m) for b, m in zip(res['Ben'], res['Moose']))
      print(ans)
      

      输出:

      31
      

      【讨论】:

      • 如何为字典中的每个 res[value] 执行此操作?有数百个键和值,我需要找到所有它们的点积以确定哪些是最高的。如果我尝试指定我的键,这很有效,但是我可以为每个键做些什么吗?
      • @DylandeHoyos 看看Conight answer,因为我已经编辑了它。如果您运行的是 3.8 或更高版本,它将适用于任何大小的 res
      【解决方案3】:

      使用zipsum 的一种方式:

      sum(int(i) * int(j) for i, j in zip(*res.values()))
      

      输出:

      31
      

      如果键数是动态的(因此是动态的列表数),您可以使用operator.mulfunctools.reduce 进行可扩展的功能:

      # Sample data with 3 keys
      
      res3 = {'Ben':['5', '0', '0', '0', '1', '4', '2'], 
              'Moose': ['5', '5', '0', '0', '0', '0', '3'],
              'Chris': ['5', '5', '0', '0', '0', '0', '3']}
      
      from operator import mul
      from functools import reduce
      
      def cummul(iterable):
          return reduce(mul, (int(i) for i in iterable))
      
      sum(cummul(it) for it in zip(*res3.values()))
      

      输出:

      143
      

      【讨论】:

        【解决方案4】:

        您可以执行类似的操作:

        res = {'Ben':['5', '0', '0', '0', '1', '4', '2'], 
        'Moose': ['5', '5', '0', '0', '0', '0', '3']}
        
        ans = {}
        for k, v in res.items():
            if(len(ans.keys())) == 0:
                ans = v
            ans_temp = [v1*v2 for v1, v2 in zip(ans, v)]
            ans = ans_temp
        
        print(sum(ans))
        
         
        
        

        这应该适用于任意长度的任何字典。

        【讨论】:

          【解决方案5】:

          对于字典中的任何键,只需使用mathzip。请注意,math.prod 需要 python 3.8 或更高版本:

          sum(math.prod(map(int, i)) for i in zip(*res.values()))
          

          【讨论】:

          • 我已为您更正了您的代码,并添加了有关 Python 3.8 或更高版本要求的注释。现在这是最好的答案...
          • 我收到此错误“AttributeError: module 'math' has no attribute 'prod'”
          • @DylandeHoyos 你需要 Python 3.8 才能拥有math.prod
          • 所以我使用运行 Python 3.7 的 Thonny,有没有办法将其更改为 3.8?或者我将如何使用这个示例代码。
          【解决方案6】:

          使用numpy 数组是个好主意,它可以让您的代码更短、更简洁、更易读:

          import numpy as np
          x = np.array([[int(j) for j in i] for i in list(res.values())])
          ans = x.prod(axis=0).sum()
          print(ans)
          

          无论res 中有多少项目,上面的代码都可以正常工作。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-01-29
            • 2023-03-17
            • 1970-01-01
            • 2015-12-21
            • 1970-01-01
            • 2020-05-30
            • 2016-01-08
            相关资源
            最近更新 更多