【问题标题】:TypeError: Calculating dot product in pythonTypeError:在python中计算点积
【发布时间】:2017-02-10 22:36:31
【问题描述】:

我需要编写一个 Python 函数,该函数返回 listAlistB 的成对乘积之和(这两个列表的长度始终相同,并且是两个整数列表)。

例如,如果listA = [1, 2, 3]listB = [4, 5, 6],点积是1*4 + 2*5 + 3*6,所以函数应该返回:32

到目前为止,我是这样编写代码的,但它会产生错误。

def dotProduct(listA, listB):
    '''
    listA: a list of numbers
    listB: a list of numbers of the same length as listA
    '''
    sum( [listA[i][0]*listB[i] for i in range(len(listB))] )

打印出来:

TypeError: 'int' 对象不可下标

如何更改此代码,以便列表中的元素可以按元素相乘?

【问题讨论】:

  • 删除[0],A是列表,不是列表
  • 如果listA 是一个整数列表,那么listA[i] 是一个整数。那你怎么办listA[i][0]
  • 试试sum(a*b for a,b in zip(listA, listB))

标签: python function python-3.x typeerror dot-product


【解决方案1】:

删除有问题的部分(尝试下标一个 int):

sum([listA[i]*listB[i] for i in range(len(listB))])

【讨论】:

    【解决方案2】:

    只需删除[0],它就可以工作:

    sum( [listA[i]*listB[i] for i in range(len(listB))] )

    更加优雅和可读,这样做:

    sum(x*y for x,y in zip(listA,listB))

    甚至更好:

    import numpy
    numpy.dot(listA, listB)
    

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 2022-01-08
      • 2014-10-24
      • 2014-08-19
      • 1970-01-01
      • 2011-06-07
      • 2021-11-19
      • 2022-01-22
      相关资源
      最近更新 更多