You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python编写递归函数实现两列表同索引元素求和并返回结果列表?

Recursive Solution for Element-wise List Addition

Got it, let's work through this recursive list addition problem step by step. The core idea with recursion here is to break the problem into tiny, repeatable steps and define a clear stopping condition (base case).

How It Works

  1. Base Case: When both input lists are empty, we return an empty list—this is where our recursion stops, since there are no more elements to add.
  2. Recursive Step: For each call, we take the first element from each list, add them together, then recursively call the function with the remaining elements of both lists. We then combine the current sum with the result of the recursive call to build our final output list.

Python Implementation

Here's the code that does exactly what you need:

def recursive_add(list1, list2):
    # Base case: no elements left in either list
    if not list1 and not list2:
        return []
    
    # Add the first elements of both lists, then recurse on the rest
    return [list1[0] + list2[0]] + recursive_add(list1[1:], list2[1:])

Test It Out

If we run this with your example inputs:

list1 = [1, 2, 3]
list2 = [2, 4, 6]
print(recursive_add(list1, list2))  # Output: [3, 6, 9]

Edge Case Note

This assumes your input lists are always the same length. If you need to handle cases where lists are different lengths, you could add a check at the start (like raising an error) or adjust the base case to return the remaining elements of the longer list (though that changes the behavior a bit). For your specific example, though, the code above works perfectly.

内容的提问来源于stack exchange,提问作者Jakeyyyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 21:37:33