我需要编写一个Python函数,返回listA
和listB
(两个列表将始终具有相同的长度并且是两个整数列表)的成对乘积之和。TypeError:在Python中计算点积
例如,如果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' object is not subscriptable
我怎样才能改变这种代码,以便在列表中的元素可以成倍元素方面?
移除'[0]',A是一个列表,而不是列表 – marcadian
的列表。如果'listA'是整数列表,然后'listA的[I]'是一个整数。那么你怎么做'listA [i] [0]'? –
试试'sum(a * b for a,b in zip(listA,listB))' – hpaulj