Home > Software design >  Finding the index of the minimum value in a list of arrays with different length
Finding the index of the minimum value in a list of arrays with different length

Time:12-13

Let's say I have a list with multiple arrays of different length:

L = [
  array([-10, -8, -3, 2, 1, 5, 12]),
  array([-9, -4, -1, 3, 5]),
  array([-11, -5, -4, 0, 1, 5, 7, 13, 18, 22])
]

How can I find the index of the lowest value the most efficiently?

For my example, the minimum value is -11 and the index is (2, 0), so the output should be (0, 2).

CodePudding user response:

A possible solution, which needs preprocessing the list of arrays with padding, because of the unequal lengths of the arrays in L:

L = [
  np.array([-10, -8, -3, 2, 1, 5, 12]),
  np.array([-9, -4, -1, 3, 5]),
  np.array([-11, -5, -4, 0, 1, 5, 7, 13, 18, 22])
]

max_size = np.max([x.size for x in L])
max_value = np.max([np.max(x) for x in L])

L_padded = [np.pad(x, (0, max_size - x.size), 
                   constant_values= 1 max_value) for x in L]
L_2d = np.array(L_padded)

min_index = np.unravel_index(L_2d.argmin(), L_2d.shape)
(min_index[0], min_index[1])
  • Related