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

Python实现sum_2D_list函数:二维列表求和报错求助

解决sum_2D_list函数实现的NameError及逻辑问题

错误原因分析

  • 你没有在sum_2D_list函数内部编写任何求和逻辑,函数体是空的,这是根本问题。
  • 你在函数外定义的twoD_list是求和后的数值,而函数要求接收二维列表作为参数,传数值进去完全不符合要求。
  • NameError大概率是代码顺序问题——比如调用sum_2D_list(twoD_list)时,twoD_list变量还没被定义,或者变量名拼写错误,但核心还是没实现函数逻辑。

正确实现方式

下面提供两种常用的实现思路:

方法1:嵌套循环(直观易懂)

list_of_lists = [[1,4,54], [23,25], [64,11,23], [53,2,6,45]]
print(list_of_lists)

def sum_2D_list(twoD_list):
    """
    A function that takes in a 2-dimensional list (i.e., a list of lists) and returns the total sum of all the numerical elements as a single number.

    Parameters
    ----------
    twoD_list: A list of list (i.e., a 2-dimensional list)
    
    Returns
    -------
    total: the sum of all the numerical elements in all the sublists
    """
    total = 0
    # 遍历每个子列表
    for sublist in twoD_list:
        # 遍历子列表中的每个元素
        for num in sublist:
            total += num
    return total

# 调用函数并输出结果
print(sum_2D_list(list_of_lists))  # 输出:310

方法2:利用sum嵌套(简洁高效)

list_of_lists = [[1,4,54], [23,25], [64,11,23], [53,2,6,45]]
print(list_of_lists)

def sum_2D_list(twoD_list):
    """
    A function that takes in a 2-dimensional list (i.e., a list of lists) and returns the total sum of all the numerical elements as a single number.

    Parameters
    ----------
    twoD_list: A list of list (i.e., a 2-dimensional list)
    
    Returns
    -------
    total: the sum of all the numerical elements in all the sublists
    """
    # 先求每个子列表的和,再把这些和加起来
    return sum(sum(sublist) for sublist in twoD_list)

# 调用函数
print(sum_2D_list(list_of_lists))  # 输出:310

也可以用生成器表达式直接遍历所有元素求和,效果一致:

return sum(num for sublist in twoD_list for num in sublist)

注意事项

  • 不要混淆函数参数和外部变量:函数的twoD_list是参数,调用时要传入原始的二维列表(比如list_of_lists),而不是求和后的数值。
  • 尽量避免用sum(twoD_list, [])这种方式展平列表,因为每次拼接列表都会生成新对象,对于大列表来说效率很低。

内容的提问来源于stack exchange,提问作者Python.noob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:07:55