【问题标题】:Is there a way to sum up all the columns and rows in a 2d array without using np.sum()?有没有办法在不使用 np.sum() 的情况下对二维数组中的所有列和行求和?
【发布时间】:2022-12-06 01:53:13
【问题描述】:

这是我当前的代码:

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

def np_sum_rows(M):  
  rows = []
  for i in range(len(M)):
    rows = M[i, 0:len(M[0])
  return rows.sum()

我希望函数返回一个向量 [6 15]。但是,for 循环只能存储和返回 15。 我被这个问题难住了,除了使用 for 循环之外想不出别的办法。

【问题讨论】:

  • 你为什么不想使用 np.sum?这是对 numpy 数组求和的最快和推荐的方法。您可以指定 axis 参数以获得行或列的总和

标签: python numpy


【解决方案1】:

您可以使用列表理解对二维数组中的行求和并返回总和列表。这是一种方法:

def sum_rows(M):
    return [sum(row) for row in M]

此函数接受二维数组 M 并返回 M 中每一行的总和列表。

以下是如何使用此功能的示例:

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

【讨论】:

  • 嗯,谢谢。你能想出一种不用列表理解的方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多