0
如何創建數組並將其傳遞給函數,讓函數對集合中的每個數組執行操作並將數組(可能以集合形式)返回給常規?數組需要保持自己的身份(通過引用傳入和傳出操作函數)。這將幫助我清理並壓縮當前的代碼。我不是一個專業的程序員,所以我意識到我的代碼可以大大改善。任何指導表示讚賞。將數組的集合傳遞給函數參數
的當前的代碼示例:
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
謝謝@aws_apprentice,我會試試這個。 – JWS