首页 > 解决方案 > 如何动态减去numpy数组

问题描述

我有一个方法可以返回一些像下面这样的 numpy 数组

def numpy_array():
  ......
  ......
  return true, test_1, test_2, test_3

我有另一种方法可以计算下面true的减法rest of the arrays

def subtraction():
  true, test_1, test_2, test_3 = numpy_array()
  sub_1 = np.subtract(true, test_1)
  sub_2 = np.subtract(true, test_2)
  ......
  ......
  return sub_1, sub_2

问题是,我的方法中可能有很多数组def numpy_array()。我想以def subtraction()动态的方式编写该方法。这样我就不需要手动减去数组(np.subtract(true, test_1),np.subtract(true, test_2)等)。

你能告诉我我该怎么做吗?

标签: arrayspython-3.xnumpy

解决方案


numpy_array或任何具有多个参数的 python 函数将返回一个元组。然后,您可以遍历元组以获得所需的差异:

def subtraction():
  matrices = numpy_array()
  # a tuple of some number of numpy arrays

  first = matrices[0]  
  # the first array, 'true' in question

  result = [first - matrices[i] for i in range(1,len(matrices))]
  # the difference between the first and subsequent arrays

  return tuple(result)

推荐阅读