繁体   English   中英

如何将一个字符串中的数字与另一个等长字符串相乘,然后在Python中添加每个乘积

[英]How to Multiply the numbers within a string with another string of equal length and then add each product in Python

我正在尝试编写一个函数,该函数将两个长度相等的字符串中的每个元素相乘,并将它们彼此相乘,然后将每个乘积相加,以获得单个答案。 vector1 = [1、2、3] vector2 = [4、5、6]

例如,上面将是(1 * 4)+(2 * 5)+(3 * 6)= 32

到目前为止,这就是我所拥有的:

vector1 = [1, 2, 3]
vector2 = [4, 5, 6]
ans = 0


if len(vector1) == 0 or len(vector2) == 0:
    print("Invalid vectors")
elif len(vector1) != len(vector2):
    print("Invalid vectors")
else:
    for i in range (len(vector1)):
        temp = vector1(i) * vector2(i)
        ans = ans + temp

该代码在编译时给我以下错误:

TypeError:“列表”对象不可调用

我试图将上面的代码更改为更像

vector1 = [1, 2, 3]
vector2 = [4, 5, 6]
ans = 0


if len(vector1) == 0 or len(vector2) == 0:
    print("Invalid vectors")
elif len(vector1) != len(vector2):
    print("Invalid vectors")
else:
    for i in range (len(vector1)) and i in range(len(vector2)):
        temp = vector1(i) * vector2(i)
        ans = ans + temp

但这也不起作用。 我在这里做错了什么?

编辑:通过Python Visualizer运行代码后,以下行在这里给了我特定的问题:

temp = vector1(i)* vector2(i)

zipsum ,还需要将其强制转换为int,前提是您拥有数字字符串:

def func(s1, s2):
    if len(s1) != len(s2):
        raise ValueError("Strings must be the same length")
    return sum(int(i) * int(j) for i,j in zip(s1, s2))

zip仍适用于长度不均匀的字符串,但如果长度相同,则ValueError可能是最合适的响应。

您自己的代码中的错误是您尝试建立索引的方式:

temp = vector1(i) * vector2(i)

应该:

temp = vector1[i] * vector2[i]

vector1(i)试图调用列表,就好像它是对函数的引用一样。 [i]实际上索引列表。 这是为zip量身定制的,但是如果要使用for循环和索引,则应使用enumerate:

def func(s1, s2):
    if len(s1) != len(s2):
        raise ValueError("Strings must be the same length")
    total = 0
    for ind, ele in enumerate(s1):
        total += int(ele) * int(s2[ind])
    return total

您的代码的更正版本。

vector1 = [1, 2, 3]
vector2 = [4, 5, 6]
ans = 0


if len(vector1) == 0 or len(vector2) == 0:
    print("Invalid vectors")
elif len(vector1) != len(vector2):
    print("Invalid vectors")
else:
    for i in range(len(vector1)):
        temp = vector1[i] * vector2[i]
        ans += temp
print ans

您要做的就是将vector1(i)更改为vector[i] ,以访问列表中索引i处的元素

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM