如果要将向量(或数组)作为输入传递给某个用户定义的函数以对它们进行一些操作,则可以传递组件:
def sample(X_0,Y_0)
#here X_0 and Y_0 are some components of the arrays X and Y
#do some operations with those components of X and Y like
scalar= X_0+Y_0
return scalar
number=sample(X[0,0],Y[0,0])
或者传递向量并在函数内部分解:
def sample(X,Y)
#here X and Y are arrays
#do some operations like
scalar=X[0,0]+Y[0,0]
return scalar
number=sample(X,Y)
哪种方法是首选方法,为什么?
在您的特定情况下,当您将结果绑定到 scalar
时,两个输出之间绝对没有区别。在 python 中,你倾向于按引用传递数组和列表,按值传递原语。那么,您什么时候可以看到差异呢?
考虑以下函数:
>>> def manipulateX(X):
... X[len(X)-1] = -1
... return X
...
使用列表调用manipulateX
(如下所示)时,您会看到该列表也作:
>>> x = [1, 2, 3, 4]
>>> manipulateX(x)
[1, 2, 3, -1]
>>> x
[1, 2, 3, -1]
但是,如果您定义一个在基元上运行的函数
>>> def manipulateY(Y):
... Y += 20
... return Y
...
并使用集合中的项目(列表、数组)等调用它:
>>> manipulateY(x[0])
21
>>> x
[1, 2, 3, -1]
>>>
您会看到x[0]
保持不变。在您的情况下,当您将结果绑定到scalar
您看不到任何区别。在这两种情况下,您的内存使用量也相同。如果您没有将结果绑定到scalar
则取决于您是否希望x[0]
和y[0]
静音。