首页 > 解决方案 > 如何创建一个递归函数,返回给定两个列表的相同索引的总和列表。?

问题描述

如何创建一个递归函数,返回给定两个列表的相同索引的总和列表。?

我只想让它成为一个递归函数。

例如:

list1 = [1,2,3]
list2 = [2,4,6]

递归函数将返回一个新列表 [3,6,9]

语言也应该是python。

谢谢你。我只是很难弄清楚。

标签: pythonrecursion

解决方案


一种方法:

def recursive_sum(a, b):
    
    # if one of the list is empty return the empty list
    if not a or not b:
        return []
    # find the sum of each of the first elements
    val = a[0] + b[0]
    
    # return the concatenation of the first sum with the recursive sum for the rest of the lists 
    return [val, *recursive_sum(a[1:], b[1:])]

输出

[3, 6, 9]

作为@Stef 建议的替代方案,请使用:

def recursive_sum(a, b):
    if not a or not b:
        return []
    return [a[0] + b[0]] + recursive_sum(a[1:], b[1:])

表达方式:

*recursive_sum(a[1:], b[1:])

被称为拆包,基本上可以说 [1, 2, 3]相当于[1, *[2, 3]],请参阅此链接以获取更多信息。


推荐阅读