列表中的元素相乘
multiply element in list
我有一个列表 [1.05, 1.06, 1.08, 1.01, 1.29, 1.07, 1.06]
我想让一个函数将列表中的任何元素 i 乘以所有下一个元素 i+1 直到列表末尾。
示例:函数(2),它将return (1.08*1.01*1.29*1.07*1.06)
的结果
我找到了这个,但是它 return 是 NoneType,所以我不能使用这个函数编辑的值 return。
谢谢,
def multiply(j,n):
total=1
for i in range(j,len(n)):
total*=n[i]
if total is not None:
print (total)
如果需要 pandas
先解决 select by iloc
and then use 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,请使用 中的解决方案 - 而不是 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
我有一个列表 [1.05, 1.06, 1.08, 1.01, 1.29, 1.07, 1.06] 我想让一个函数将列表中的任何元素 i 乘以所有下一个元素 i+1 直到列表末尾。 示例:函数(2),它将return (1.08*1.01*1.29*1.07*1.06)
的结果我找到了这个,但是它 return 是 NoneType,所以我不能使用这个函数编辑的值 return。 谢谢,
def multiply(j,n):
total=1
for i in range(j,len(n)):
total*=n[i]
if total is not None:
print (total)
如果需要 pandas
先解决 select by iloc
and then use 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,请使用 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