将一组数组传递给函数参数

时间:2017-09-03 14:59:33

标签: python arrays python-3.x multidimensional-array

如何创建数组集合并将其传递给函数,让函数对集合中的每个数组执行操作,并将数组(可能以集合形式)返回到例程?数组需要保持其身份(通过引用传递给操作函数和从操作函数传递)。这将帮助我清理和压缩我当前的代码。我不是专业的程序员,所以我意识到我的代码可以大大改进。任何指导都表示赞赏。

当前代码的示例:

import numpy as np

# Function that performs some operation on array (matrix)
def addLine(x):
    x = np.vstack([x,np.random.rand(1,5)])
    return x

def mainLoop():
    A = np.zeros((1,5),dtype=np.float32)
    B = np.ones((1,5),dtype=np.float32)
    C = np.ones((1,5),dtype=np.float32)

    # Do stuff

    A = addLine(A)
    B = addLine(B)
    C = addLine(C)

我想做什么:

# Function that accepts a collection of arrays as argument, performs 
# operation, and returns modified arrays to the same identity / name     
def addLines(x):
    for n in range(len(x)):
        x[n] = addLine(x)
        return x[n]

def mainLoop():
    A = np.zeros((1,5),dtype=np.float32)
    B = np.ones((1,5),dtype=np.float32)
    C = np.ones((1,5),dtype=np.float32)

    # Do stuff
    # Create a collection of all arrays to perform operations on
    AllArrays = [A,B,C]

    # Pass collection of arrays to function (I likely need a for loop here)
    AllArrays = addLines(AllArrays)

    # Perform further operations on individual arrays
    A = A+2
    B = B+1
    C = C-1

1 个答案:

答案 0 :(得分:0)

这种轻微的改变怎么样?

def addLine(*args):
    args = map(lambda x: np.vstack([x,np.random.rand(1,5)]), *args)
    return args

AllArrays = addLine(AllArrays)

A, B, C = AllArrays

A

array([[ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.66237197,  0.07125813,  0.5454597 ,  0.44901189,  0.89820099]])