在Python中实现Lisp风格子列表求和函数时遇TypeError错误求助
Hey there! Let's figure out why you're hitting that TypeError and get your sublist sum function working in Python. That error pops up when you try to treat a plain integer like a list—say, using square brackets to index it, like my_int[0]—which doesn't make sense because integers aren't subscriptable. Chances are your initial Python attempt tried to mirror Lisp's car/cdr logic without checking if you're dealing with a list vs. a number.
First, let's align with your Common Lisp approach: you have a helper to sum numbers in a single sublist, then a main function that builds a list of those sums in order. Let's translate that correctly, then also show a simpler, more Pythonic way to do it.
1. Recursive Implementation (Matching Your Lisp Style)
Here's a recursive setup that mirrors your Lisp code, with guards to avoid the integer subscript mistake:
First, the helper function to sum numbers in a single sublist (just like your sum-numbers):
def sum_numbers(sublist): # Base case: empty sublist sums to 0 if not sublist: return 0 # Add the first number to the sum of the rest of the sublist return sublist[0] + sum_numbers(sublist[1:])
Then the main function that processes the list of sublists:
def sum_sublists(input_list): # Base case: empty input list returns empty result if not input_list: return [] # Calculate sum of the first sublist, then recurse on the remaining sublists return [sum_numbers(input_list[0])] + sum_sublists(input_list[1:])
The key here is ensuring sum_numbers only ever gets passed a sublist (a list of numbers), not individual integers. That way, we never try to index an integer, which was causing your original error.
2. Idiomatic Python (No Recursion Needed)
Python has built-in tools that make this way simpler—no need to reinvent the recursive wheel. A list comprehension with the built-in sum() function does exactly what you need:
def sum_sublists(input_list): return [sum(sublist) for sublist in input_list]
This one-liner iterates over each sublist in your input, calculates its sum with sum(), and collects all those sums in the same order as the original sublists. It's concise, readable, and avoids recursion-related bugs.
Example Test Run
Let's test with a sample input to confirm it works:
test_input = [[1, 2, 3], [4, 5], [6, 7, 8]] print(sum_sublists(test_input)) # Output: [6, 9, 21]
That's exactly the ordered list of sublist sums you're looking for.
Content of the question originates from Stack Exchange, question author Nikitonix

