2016-11-22 65 views
0

我有一個列表[1.05,1.06,1.08,1.01,1.29,1.07,1.06] 我想做一個函數,將列表中的任意元素i乘以下一個元素i + 1,直到結束的名單。例如:函數(2),它會返回結果(1.08 * 1.01 * 1.29 * 1.07 * 1.06)列表中的乘法元素

我發現這個,但它返回NoneType,所以我不能使用這個返回的值功能。 謝謝,

def multiply(j,n): 
    total=1 
    for i in range(j,len(n)): 
     total*=n[i] 
    if total is not None: 
     print (total) 
+0

爲什麼熊貓標籤? 'list'是'series'? – jezrael

+0

將「return total」添加到函數的末尾,以便它返回一個值(儘管我不確定它是否正在執行您想要的操作)。 –

回答

1

如果需要pandas解決方案首先由iloc選擇,然後使用prod

s = pd.Series([1,2,3,4]) 
print (s) 
0 1 
1 2 
2 3 
3 4 
dtype: int64 

print (s.iloc[2:]) 
2 3 
3 4 
dtype: int64 

print (s.iloc[2:].prod()) 
12 

但如果需要純Python,使用的解決方案從Benjamin comment - 而不是print - return

m = [1,2,3,4] 

def multiply(j,n): 
    total=1 
    for i in range(j,len(n)): 
     total*=n[i] 
    return total 

print (multiply(2,m)) 
12 
+0

總是從來沒有在這種情況下,你可以刪除'if'語句 – Tim

+0

@TimP - 謝謝,它總是返回至少'1' – jezrael

+0

真棒!非常感謝你! – enden