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

在Python中实现Lisp风格子列表求和函数时遇TypeError错误求助

Fixing the 'int' object is not subscriptable Error in Your Python Sublist Sum Implementation

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:45:23