遍历数组列表,用作函数的输入



在下面的代码中,我如何遍历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)

您可以使用列表推导式:

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]))

由于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直接创建输出数组,而无需显式遍历对。