簡體   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