在下面的代碼中,我如何迭代y以獲取所有 5 組(每組 2 個陣列)用作 的輸入func?
我知道我可以這樣做:
func(y[0],y[1])
func(y[2],y[3])...etc....
但是我不能對上面的行進行編碼,因為我可以有數百個陣列 y
import numpy as np
import itertools
# creating an array with 100 samples
array = np.random.rand(100)
# making the array an iterator
iter_array = iter(array)
# Cerating a list of list to store 10 list of 10 elements each
n = 10
result = [[] for _ in range(n)]
# Starting the list creating
for _ in itertools.repeat(None, 10):
for i in range(n):
result[i].append(next(iter_array))
# Casting the lists to arrays
y=np.array([np.array(xi) for xi in result], dtype=object)
#list to store the results of the calculation below
result_func =[]
#applying a function take takes 2 arrays as input
#I have 10 arrays within y, so I need to perfom the function below 5 times: [0,1],[2,3],[4,5],[6,7],[8,9]
a = func(y[0],y[1])
# Saving the result
result_func.append(a)
uj5u.com熱心網友回復:
您可以使用串列理解:
result_func = [func(y[i], y[i 1]) for i in range(0, 10, 2)]
或一般的 for 回圈:
for i in range(0, 10, 2):
result_func.append(funct(y[i], y[i 1]))
uj5u.com熱心網友回復:
由于 numpy 在整形時的填充順序,您可以將陣列整形為
- 可變深度(取決于陣列的數量)
- 兩個高度
- 與每個輸入行中的元素數相同的寬度
因此,在填充時它將填充兩行,然后需要將深度增加一。
迭代這個陣列會產生一系列矩陣(每個深度層一個)。每個矩陣有兩行,結果是y[0], y[1]、y[2], y[3]、 等等。
例如,假設內部陣列的長度為 6,總共有 8 個(因此有 4 個函式呼叫):
import numpy as np
elems_in_row = 6
y = np.array(
[[1,2,3,4,5,6],
[7,8,9,10,11,12],
[13,14,15,16,17,18],
[19,20,21,22,23,24],
[25,26,27,28,29,30],
[31,32,33,34,35,36],
[37,38,39,40,41,42],
[43,44,45,46,47,48],
])
# the `-1` makes the number of rows be inferred from the input array.
y2 = y.reshape((-1,2,elems_in_row))
for ar1,ar2 in y2:
print("1st:", ar1)
print("2nd:", ar2)
print("")
輸出:
1st: [1 2 3 4 5 6]
2nd: [ 7 8 9 10 11 12]
1st: [13 14 15 16 17 18]
2nd: [19 20 21 22 23 24]
1st: [25 26 27 28 29 30]
2nd: [31 32 33 34 35 36]
1st: [37 38 39 40 41 42]
2nd: [43 44 45 46 47 48]
作為旁注,如果您的函式輸出簡單的值(如整數或浮點數)并且沒有像 IO 那樣的副作用,則可能可以使用apply_along_axis直接創建輸出陣列而無需顯式迭代這些對。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/335461.html
