【问题标题】:How to subtract numpy arrays dynamically如何动态减去numpy数组
【发布时间】:2021-05-10 22:15:40
【问题描述】:

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

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

我有另一种方法可以计算truerest 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) 等)。

你能告诉我该怎么做吗?

【问题讨论】:

  • 如果您编写没有输入值的函数,无论如何您都会遇到问题。最好是 new_arr = subtraction(arr1, arr2)... 但 numpy 已经为您编写了该函数,np.subtract。我没有看到你写的函数中的值
  • 我不明白你的想法。您介意详细说明吗?
  • 您是否考虑过将您的 test_N 数组转换为单个 3 x X 数组?如果是这样,numpy 的广播功能可以一步完成所有这些减法。
  • True-True 应该做什么?
  • @hpaulj 什么都没有!

标签: arrays python-3.x numpy


【解决方案1】:

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)

【讨论】:

  • 非常感谢。但是使用tuple的原因是什么?
  • 因为否则它将返回一个列表对象,由列表理解创建。在 python 中返回多个参数时,元组是默认值,但如果你想要一个列表,则不需要那个位。
猜你喜欢
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多