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

不使用np.sum()实现二维数组行列求和?现有代码问题求助

不使用np.sum()实现二维数组的行/列求和

首先看你代码的问题:循环里每次直接把rows赋值为当前行M[i, ...],最后只保留了最后一行,调用sum()自然只会返回最后一行的和15。要得到每行的和组成的向量,需要手动计算每行的元素总和并收集结果。

行求和实现(手动循环)

import numpy as np

M = np.array([[1, 2, 3],
              [4, 5, 6]])

def sum_rows(M):
    row_sums = []
    # 遍历每一行
    for row in M:
        current_sum = 0
        # 累加当前行的所有元素
        for num in row:
            current_sum += num
        row_sums.append(current_sum)
    # 转成numpy数组返回
    return np.array(row_sums)

print(sum_rows(M))  # 输出: [ 6 15]

列求和实现(手动循环)

如果要计算每列的和,思路类似,遍历每一列的元素累加:

def sum_cols(M):
    col_sums = []
    # 获取数组的列数
    col_count = M.shape[1]
    # 遍历每一列索引
    for j in range(col_count):
        current_sum = 0
        # 遍历每一行,取当前列的元素
        for row in M:
            current_sum += row[j]
        col_sums.append(current_sum)
    return np.array(col_sums)

print(sum_cols(M))  # 输出: [5 7 9]

无循环实现(利用矩阵运算)

如果不想用嵌套循环,也可以借助numpy的矩阵乘法,不用np.sum()也能实现:

  • 行求和:用数组乘以全1的列向量,等价于每行元素相加
def sum_rows_no_loop(M):
    return M @ np.ones(M.shape[1], dtype=M.dtype)

print(sum_rows_no_loop(M))  # 输出: [ 6. 15.]
  • 列求和:用全1行向量乘原数组,等价于每列元素相加
def sum_cols_no_loop(M):
    return np.ones(M.shape[0], dtype=M.dtype) @ M

print(sum_cols_no_loop(M))  # 输出: [5. 7. 9.]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:01:37