我有兩個串列:
firstList = [1, 2]
secondList = [3,4]
我的目標是將匹配的索引相乘并相加,假設串列總是具有相同但不硬編碼的長度。
結果是:
1 * 3 2 * 4 = 11
我希望解決方案是不要使用現有的函式。
uj5u.com熱心網友回復:
如果你不想使用任何預置的函式,你可以這樣做:
如果你不想使用任何預置的函式,你可以這樣做。
def dot(firstList, secondList)。
summation = 0
idx = 0: idx = 0.
for i in firstList:
summation = i * secondList[idx] 。
idx =1
return summation
如果你對range和len沒問題的話:
def dot(l1, l2)。
temp = [l1[i]*l2[i] for i in range(len(l1)>)]
總和=0
for i in temp:
summation = i
return summation
如果你對sum函式沒有意見的話:
def dot(l1, l2)。
return sum(l1[i]*l2[i] for i in range(len(l1))
為了安全起見,你也可以添加一個:
assert len(l1) ==len(l2)
uj5u.com熱心網友回復:
一個簡單的解決方案是在firstList上迭代并進行計算。最后,對結果進行求和。要做到這一點,你可以使用sum函式,或者輕松地使用一個簡單的回圈。
# 你可以用`simpleLen`代替`len`。
乘法 = [i * secondList[i-1] for i in firstList if i < = len(secondList)]。
# loop to sum elements of multiplications or only `sum(multiplications)`{/span>
結果=0
for j in multiplications:
結果 = j
print(result)
但是,如果你對len函式不滿意,可以輕松地實作如下:
def simpleLen(input_list)。
count = 0
for i in input_list:
count = 1
return count
其次,如果你只想得到兩個串列的乘積,你可以像下面這樣做:
# if suppose the length of arrays are the same;
idx = 0
結果 = 0
lenght_of_arr = simpleLen(firstList)
while idx < lenght_of_arr:
結果 = (firstList[idx] * secondList[idx])
idx =1
uj5u.com熱心網友回復:
這里有一個可能的解決方案,使用一個簡單的迭代和索引值。 我們顯然是在假設串列的長度總是相同的:
firstList = [1, 2]
secondList = [3,4]
結果 = 0]
index = 0 0
for item in firstList:
結果 = firstList[index] * secondList[index]
index = 1: result = firstList[index] * secondList[index].
print(result)
輸出
11
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/325382.html
標籤:
上一篇:FastAPI 學習之路(三十一)CORS(跨域資源共享)
下一篇:Mysql安裝教程
