Home > Software design >  Iterating over a list of arrays to use as input in a function
Iterating over a list of arrays to use as input in a function

Time:10-25

In the code below, how can I iterate over y to get all the 5 groups of 2 arrays each to use as input to func?

I know I could just do :

func(y[0],y[1])
func(y[2],y[3])...etc....

But I cant code the lines above because I can have hundreds of arrays in 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)

CodePudding user response:

You could use list comprehension:

result_func = [func(y[i], y[i 1]) for i in range(0, 10, 2)]

or the general for loop:

 for i in range(0, 10, 2):
    result_func.append(funct(y[i], y[i 1]))

CodePudding user response:

Because of numpy's fill-order when reshaping, you could reshape the array to have

  • a variable depth (depending on the number of arrays)
  • a height of two
  • the same width as the number of elements in each input row

Thus when filling it will fill two rows before needing to increase the depth by one.

Iterating over this array results in a series of matrices (one for each depthwise layer). Each matrix has two rows, which comes out to be y[0], y[1], y[2], y[3], and so on.

For examples sake say the inner arrays each have length 6, and that there are 8 of them in total (so that there are 4 function calls):

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("")

output:

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]

As a sidenote, if your function outputs simple values (like integers or floats) and does not have side-effects like IO, it may perhaps be possible to use apply_along_axis to create the output array directly without explicitly iterating over the pairs.

  • Related