简体   繁体   English

将数组作为输入传递给用户定义的函数

[英]Passing arrays as input to user defined functions

If you want to pass vectors (or arrays) as input to some user defined function to make some operations with them, you can pass the components: 如果要将向量(或数组)作为输入传递给某些用户定义的函数以对其进行一些操作,则可以传递以下组件:

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])

or pass the vectors and decompose then inside the function: 或传递向量并在函数内分解:

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)

which is the preferred method and why? 哪个是首选方法,为什么?

In your specific case, there is absolutely no difference between the two outputs as you bind the results to scalar . 在您的特定情况下,将结果绑定到scalar ,两个输出之间绝对没有区别。 In python, you tend to pass arrays and lists by reference and primitives by value. 在python中,您倾向于按引用传递数组和列表,按值传递基元。 So when can you expect to see a difference? 那么您何时可以期望看到不同呢?

Consider the function: 考虑以下功能:

>>> def manipulateX(X):
...     X[len(X)-1] = -1
...     return X
... 

When you call manipulateX with a list (as follows), you see that the list is also manipulated: 当您使用列表调用manipulateX时(如下所示),您会看到列表也受到了操纵:

>>> x = [1, 2, 3, 4]
>>> manipulateX(x)
[1, 2, 3, -1]
>>> x
[1, 2, 3, -1]

However, if you define a function which operates on a primitive 但是,如果您定义了一个对原语进行操作的函数

>>> def manipulateY(Y):
...     Y += 20
...     return Y
... 

and call it with an item in a collection (list, array) etc: 并使用集合(列表,数组)等中的项目调用它:

>>> manipulateY(x[0])
21
>>> x
[1, 2, 3, -1]
>>> 

You see that x[0] remains unchanged. 您会看到x[0]保持不变。 In your case as you bind your results to scalar you don't see any difference. 在您的情况下,当您将结果绑定到scalar ,看不到任何区别。 In both the cases, your memory usage is also the same. 在这两种情况下,您的内存使用情况也相同。 If you weren't binding the results to scalar then it depends on whether you want x[0] and y[0] to be muted. 如果没有将结果绑定到scalar则取决于是否要静音x[0]y[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM