我已經定義了一個輸出兩個陣列 [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,所以是的,我確定我錯過了一些非常基本的東西。
uj5u.com熱心網友回復:
您必須確保您的函式首先回傳陣列,例如:
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
uj5u.com熱心網友回復:
一個基本的嵌套回圈
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)]
請注意, myfunc采用兩個值(標量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.])]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491053.html
上一篇:在反應傳單中內置標記圖示型別
