TypeError: Calculating dot product in python

TypeError: Calculating dot product in python

我需要编写一个 Python 函数,其中 return 是 listAlistB 的成对乘积之和(这两个列表将始终具有相同的length 和两个整数列表)。

例如listA = [1, 2, 3]listB = [4, 5, 6],点积为1*4 + 2*5 + 3*6,那么函数应该return: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' object is not subscriptable

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

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

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

只需删除 [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)