[英]Passing a collection of arrays to function argument
如何創建數組的集合並將其傳遞給函數,讓函數對集合中的每個數組執行操作,然后將數組(可能以集合形式)返回例程? 數組需要保持其標識(通過引用與操作函數進行傳遞)。 這將幫助我清理並壓縮當前代碼。 我不是專業的程序員,所以我意識到我的代碼可以得到極大的改進。 任何指導表示贊賞。
當前代碼示例:
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
這個微小的變化怎么樣?
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.