使用相同数组

时间:2016-09-21 12:44:23

标签: python arrays numpy

我是Python的新手,我试图习惯于执行Python的数组操作而不是循环遍历数组。下面是我正在做的循环操作的一个例子,但我无法找到一个不依赖循环的合适的纯数组操作:

import numpy as np

def f(arg1, arg2):
  # an arbitrary function


def myFunction(a1DNumpyArray):
  A = a1DNumpyArray      

  # Create a square array with each dimension the size of the argument array.
  B = np.zeros((A.size, A.size))

  # Function f is a function of two elements of the 1D array. For each 
  # element, i, I want to perform the function on it and every element 
  # before it, and store the result in the square array, multiplied by 
  # the difference between the ith and (i-1)th element.
  for i in range(A.size):
    B[i,:i] = f(A[i], A[:i])*(A[i]-A[i-1])

  # Sum through j and return full sums as 1D array.
  return np.sum(B, axis=0)

简而言之,我正在集成一个函数,该函数将相同数组的两个元素作为参数,返回一个积分结果数组。

有没有更简洁的方法来做到这一点,而不使用循环?

1 个答案:

答案 0 :(得分:0)

使用任意f函数,并且通过传递循环使此[i, :i]业务变得复杂。

大多数快速编译的numpy操作都在整个数组或整行和/或列上工作,并且有效地并行执行。本质上连续的循环(一个循环的值取决于前一个循环)不适合。并且每个循环中不同大小的列表或数组也是“矢量化”的良好指标。会很难。

for i in range(A.size):
    B[i,:i] = f(A[i], A[:i])*(A[i]-A[i-1])

使用示例A和已知f(简单为arg1*arg2),我生成B数组,并查找处理{的模式{1}}作为一个整体。乍一看,您的B看起来像是一个较低的三角形。有一些功能可以帮助索引那些。但最终的总和可能会改变这种情况。

有时我会采用自下而上的方法解决这些问题,首先尝试删除内部循环。但在这种情况下,我认为需要某种全局的方法。