python - 如何创建一个递归函数,返回给定两个列表的相同索引的总和列表。?
问题描述
如何创建一个递归函数,返回给定两个列表的相同索引的总和列表。?
我只想让它成为一个递归函数。
例如:
list1 = [1,2,3]
list2 = [2,4,6]
递归函数将返回一个新列表 [3,6,9]
语言也应该是python。
谢谢你。我只是很难弄清楚。
解决方案
一种方法:
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]]
,请参阅此链接以获取更多信息。
推荐阅读
- c# - 使用 Validator.TryValidateObject 访问模型中的 IValidatableObject.Validate 方法
- django - django模型中的文件字段,隐藏文件链接并清除模板中的框
- node.js - 当我尝试执行 npm install 时出现问题
- confluence - 如何避免在用户宏中打印 IF 条件的结果
- javascript - 暴露自己的命令句柄同时转发 ref 的 React HOC 如何检测被包装的组件是否可以获取 ref?
- java - 为什么这段代码没有抛出 nullPointerException?
- reactjs - 使用 react-paypal-js 禁用送货地址
- javascript - 来自字符串变量名的 Javascript 类
- rust - 如何从 frame_system::Config 访问存储?
- javascript - 有没有办法在 Windows WebView2 组件中进行自定义资源加载?例如,像自定义 URL 方案?