You need to enable JavaScript to run this app. 如何将索引作为变量处理,提取嵌套列表指定位置元素实现列求和
优惠活动
大模型
产品
解决方案
定价
更多

如何将索引作为变量处理,提取嵌套列表指定位置元素实现列求和

嵌套列表指定索引列求和实现方案

你现有代码的错误如下:

  • 遍历子列表的过程中没有用到循环变量,直接访问外层列表numbest[index],拿到的是外层列表的第index个子列表,而非每个子列表中index位置的元素
  • 如果是Python3环境,print未加括号属于语法错误

正确实现代码

def column_sum(index, nested_list):
    total = 0
    # 遍历每个子列表
    for sub_list in nested_list:
        # 累加子列表指定索引位置的元素
        total += sub_list[index]
    return total

# 调用示例
res = column_sum(2, [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 5, 7, 9, 11]])
print(res)

运行后输出结果为16,符合需求。

也可以用内置sum函数搭配生成器表达式简化写法,代码更精简:

def column_sum(index, nested_list):
    return sum(sub[index] for sub in nested_list)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 10:36:03