【发布时间】:2017-02-10 22:36:31
【问题描述】:
我需要编写一个 Python 函数,该函数返回 listA 和 listB 的成对乘积之和(这两个列表的长度始终相同,并且是两个整数列表)。
例如,如果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