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

Python中2D Array行求和异常:仅返回最后一行的和

问题分析与解决

你的代码存在三个核心问题:

  • 仅用单个变量s存储行和,每次循环新行时会覆盖之前的结果,最终只返回最后一行的和
  • 内层for j循环完全冗余,A[i].sum()已经直接计算了当前行的总和,不需要再遍历列元素
  • 参数n未被使用,属于冗余定义

修正后的代码

如果你的A是numpy数组(从.sum()方法判断大概率是),可以直接返回每行和的列表:

def sum_row(A):
    row_sums = []
    for row in A:
        row_sums.append(row.sum())
    return row_sums

如果是普通Python列表,把row.sum()换成内置的sum(row)即可:

def sum_row(A):
    row_sums = []
    for row in A:
        row_sums.append(sum(row))
    return row_sums

使用示例

# 假设是numpy数组
import numpy as np
A = np.array([
    [3, 6, 6, 0, 9, 8],
    [4, 7, 0, 0, 7, 1],
    [5, 7, 0, 1, 4, 6],
    [2, 9, 9, 9, 9, 1]
])

row_sums = sum_row(A)
for idx, total in enumerate(row_sums):
    print(f"sum of row {idx} = {total}")

运行后会输出预期结果:

sum of row 0 = 32
sum of row 1 = 19
sum of row 2 = 23
sum of row 3 = 39

更简洁的写法

用列表推导式可以一行完成行和计算:

# numpy数组版本
row_sums = [row.sum() for row in A]

# 普通列表版本
row_sums = [sum(row) for row in A]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:35:50