简体   繁体   English

将数组的集合传递给函数参数

[英]Passing a collection of arrays to function argument

How do I create and pass a collection of arrays to a function, have the function perform an operation on each array in the collection and return the arrays (likely in collection form) back to the routine? 如何创建数组的集合并将其传递给函数,让函数对集合中的每个数组执行操作,然后将数组(可能以集合形式)返回例程? The arrays need to maintain their identity (pass to and from the operation function by reference). 数组需要保持其标识(通过引用与操作函数进行传递)。 This will help me to clean up and condense my current code. 这将帮助我清理并压缩当前代码。 I'm not a professional programmer, so I realize that my code could be drastically improved. 我不是专业的程序员,所以我意识到我的代码可以得到极大的改进。 Any guidance is appreciated. 任何指导表示赞赏。

An example of current code: 当前代码示例:

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)

What I would like to do: 我想做的是:

# 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

How about this slight change? 这个微小的变化怎么样?

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

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

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