1
我对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)
总之,我整合功能,有两个相同数组的元素作为参数,返回积分结果数组。
有没有更紧凑的方式来做到这一点,而不使用循环?
现在阅读起来比较容易。任何你想妥协的理由? – erip
我被一位资深Pythoneer告知:“不要使用循环来操作数组,使用数组操作。”显然,如果这太过于妥协易读性,我会坚持循环。 –
我想说一个更好的规则是“不要使用循环来操作数组,如果存在一个数组操作来执行你所需要的操作”。 – Kevin