Python递归遍历列表
我需要帮助创建一个递归函数,将列表中的所有项相乘。代码如下:Python递归遍历列表,python,Python,我需要帮助创建一个递归函数,将列表中的所有项相乘。代码如下: def multiply(lst): if len(lst) < 1: return 1 else: for x in range(len(lst)): return lst[x] * multiply(lst[x+1]) def倍增(lst): 如果len(lst)
def multiply(lst):
if len(lst) < 1:
return 1
else:
for x in range(len(lst)):
return lst[x] * multiply(lst[x+1])
def倍增(lst):
如果len(lst)<1:
返回1
其他:
对于范围内的x(len(lst)):
返回lst[x]*乘法(lst[x+1])
您不需要递归和循环。使用递归(不推荐,但作为演示):
或循环:
# multiply([2, 3, 4])
# product = 1
# product *= 2 (== 2)
# product *= 3 (== 6)
# product *= 4 (== 24)
def multiply(lst):
product = 1
for x in lst:
product *= x
return product
从移除循环开始。
如果len(lst)==1,则返回lst[0],否则lst[0]*乘法(lst[1:])
除非这是为了做作业,否则对类似的事情使用递归是个坏主意。非常感谢CRJOr乘法=数学。prod
:-)我假设这不会被接受为作业的答案:)
# multiply([2, 3, 4])
# product = 1
# product *= 2 (== 2)
# product *= 3 (== 6)
# product *= 4 (== 24)
def multiply(lst):
product = 1
for x in lst:
product *= x
return product