gpt4 book ai didi

python - 类型错误:在 python 中计算点积

转载 作者:太空宇宙 更新时间:2023-11-03 16:05:44 26 4
gpt4 key购买 nike

我需要编写一个 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' object is not subscriptable

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

最佳答案

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

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

关于python - 类型错误:在 python 中计算点积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39823879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com