如何将索引作为变量处理,提取嵌套列表指定位置元素实现列求和
嵌套列表指定索引列求和实现方案
你现有代码的错误如下:
- 遍历子列表的过程中没有用到循环变量,直接访问外层列表
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
相关产品推荐
相关产品推荐

