Python递归筛选列表正整数返回空列表的问题求助
Why Your Recursive Function Returns an Empty List
Let's break down the issue with your current code. The problem lies in how you're handling the result list across recursive calls:
- Each call initializes a new empty
result: Every time you runpositive(lst), you create a fresh empty list. When you append a positive element to this list, you don't combine it with the result from processing the rest of the list. - You discard the current
result: Instead of returning theresultyou built (with the positive element) plus the output ofpositive(lst[1:]), you just returnpositive(lst[1:])directly. This means all the positive elements you collected in earlier calls are lost—only the base case's empty list propagates back up.
Correct Recursive Implementation
Here's a fixed version that properly accumulates positive elements through recursion:
def positive(lst): # Base case: empty list returns empty list if not lst: return [] # If first element is positive, include it and recurse on the rest elif lst[0] > 0: return [lst[0]] + positive(lst[1:]) # If not positive, just recurse on the rest of the list else: return positive(lst[1:]) # Test it out lst = [-1, -4, 0, 3, 6] result = positive(lst) print(result) # Output: [3, 6]
How This Works:
- Base Case: When the input list is empty (
not lst), we return an empty list—this stops the recursion. - Positive Element: If the first element is greater than 0, we create a list containing that element and concatenate it with the result of processing the remaining elements (
lst[1:]). - Non-Positive Element: If the first element isn't positive, we skip it and just return the result of processing the rest of the list.
Let's walk through your test case step-by-step:
positive([-1, -4, 0, 3, 6])→-1isn't positive, so returnpositive([-4, 0, 3, 6])positive([-4, 0, 3, 6])→-4isn't positive, returnpositive([0, 3, 6])positive([0, 3, 6])→0isn't positive, returnpositive([3, 6])positive([3, 6])→3is positive, return[3] + positive([6])positive([6])→6is positive, return[6] + positive([])positive([])→ return[]- Putting it all together:
[6] + [] = [6], then[3] + [6] = [3,6], which propagates back up as the final result.
Alternative Version (Using Accumulator)
If you prefer using an accumulator to build the result (which can be more efficient for large lists), you can modify the function to take an optional accumulator parameter:
def positive(lst, acc=None): if acc is None: acc = [] if not lst: return acc if lst[0] > 0: acc.append(lst[0]) return positive(lst[1:], acc) # Test lst = [-1, -4, 0, 3, 6] print(positive(lst)) # Output: [3,6]
This version uses an accumulator list that's passed through recursive calls, appending positive elements as we go. The base case returns the fully built accumulator.
内容的提问来源于stack exchange,提问作者lililllil
相关产品推荐
相关产品推荐

