[英]Loop a function and store the output of each result
我已經定義了一個輸出兩個數組 [x] 和 [y] 的函數。 我的目標是多次調用該函數(在本例中為 10 次)並將這些輸出中的每一個存儲到不同的數組中,以便我可以平均每個數組的 x 和 y。 我已經開始我的代碼調用函數 10 次,如下所示: def myfunction() = myexamplefunction; 在這個函數中,我定義了我的輸出數組 x 和 y,並且可以顯示我的函數填充了這些值。 例如,x 數組看起來像 [[0, 1, 2, 1, 2, 3, 4, 5, 6, 7, 6, 7, 8, 9, 10] 作為輸出。
Xtotal=[0] #new array that stores all the x values
Ytotal=[0] #new array that stores all the y values
for i in myfunction(range(10)):
Xtotal.append(x) #append the whole x array
Ytotal.append(y) #append the whole y array
或者我試過:
for i in range(10):
myfunction()
Xtotal.append(x) #append the whole x array
Ytotal.append(y) #append the whole y array
我已成功調用我的函數 10 次,但無法讓每個輸出嵌套在我的新數組中。 任何幫助,將不勝感激。 我正在為這個特定項目學習 python,所以是的,我確定我錯過了一些非常基本的東西。
您必須確保您的函數首先返回數組,例如:
def myfunction():
*
*
return X, Y # <-- this line
那么您必須調用此函數並將其結果放入新變量中,即:
Xtotal = []
Ytotal = []
for i in range(10):
x, y = myfunction() # <-- this line: put returned arrays X, Y in x, y
Xtotal.append(x) #append the whole x array
Ytotal.append(y) #append the whole y array
一個基本的嵌套循環
alist =[]
for i in range(3):
blist = []
for j in range(4):
blist.append(func(i,j))
alist.append(blist)
或者
alist = [func(i,j) for j in range(4)] for i in range(3)]
請注意,我的func
采用兩個值(標量i
和j
),並返回一些內容,例如數字。 結果將是數字列表的列表。
您將myfunction
描述為返回 2 個數組。 但是,如果有的話,不要說任何關於它的論點(輸入)。
In [12]: def myfunction():
...: return np.arange(3), np.ones((4))
...:
In [15]: alist = []
...: for i in range(3):
...: alist.append(myfunction())
...:
In [16]: alist
Out[16]:
[(array([0, 1, 2]), array([1., 1., 1., 1.])),
(array([0, 1, 2]), array([1., 1., 1., 1.])),
(array([0, 1, 2]), array([1., 1., 1., 1.]))]
這是一個元組列表,每個元組都包含函數生成的 2 個數組。 這個結果是對還是錯?
從許多調用中收集結果的另一種方法:
In [17]: alist = []; blist = []
...: for i in range(3):
...: x,y = myfunction()
...: alist.append(x); blist.append(y)
...:
In [18]: alist
Out[18]: [array([0, 1, 2]), array([0, 1, 2]), array([0, 1, 2])]
In [19]: blist
Out[19]: [array([1., 1., 1., 1.]), array([1., 1., 1., 1.]), array([1., 1., 1., 1.])]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.