How to multiply array elements for nth arrays in Python?

I am trying to make method for creating array from nth arrays in Python . I have looked Numpy but the method seems not suit my requirement.
The following is my code works in javascript.
numArr = [[1],[12],[22],[31,32,33],[41,42]] , the result will be
[1,12,22,31,41],[1,12,22,31,42],[1,12,22,32,41],[1,12,22,32,42],[1,12,22,33,41],[1,12,22,33,42]

for (var i = 0; i < numArr.length; i++) {
    tempNumArr = new Array(totalNumArr.length * numArr[i].length);
    for (var j = 0; j < totalNumArr.length; j++) {
      for (var k = 0; k < numArr[i].length; k++) {
        tempNumArr[j * numArr[i].length + k] = new Array();
        if (i !== 0)
          tempNumArr[j * numArr[i].length + k] = totalNumArr[j].slice();

        tempNumArr[j * numArr[i].length + k].push(numArr[i][k]);
      }
    }
    totalNumArr = tempNumArr;
  }

What you’re looking for is a product of arrays

import itertools

ls = [[1],[12],[22],[31,32,33],[41,42]]

print([p for p in itertools.product(*ls)])

(gives a list of tuples, but can be easily changed to give list of lists instead)

A maybe not so obvious but pure Numpy solution, where the result is a 2D Numpy array, would be:

import numpy as np

num_arr = [[1], [12], [22], [31, 32, 33], [41, 42]]
result = np.asarray(np.meshgrid(*num_arr)).reshape(len(num_arr), -1).T
print(result)
# >>> [[ 1 12 22 31 41]
#      [ 1 12 22 31 42]
#      [ 1 12 22 32 41]
#      [ 1 12 22 32 42]
#      [ 1 12 22 33 41]
#      [ 1 12 22 33 42]]

It uses numpy.meshgrid() and follows this answer to a similar question.

What happens in detail is the following:

  1. With np.meshgrid(*num_arr) we create a list of 5 Numpy arrays, each holding 1×1×1×3×2 values. The n-th array holds the combinations of the n-th sublist of num_arr along the n-th axis and is repeated as necessary along the other axes. To make this clear, the first array contains [[[[[1, 1], [1, 1], [1, 1]]]]], the penultimate array contains [[[[[31, 31], [32, 32], [33, 33]]]]], and the last array contains [[[[[41, 42], [41, 42], [41, 42]]]]].
  2. With np.asarray(), we convert the 5-element list of 1×1×1×3×2 Numpy arrays to one 5×1×1×1×3×2 Numpy array.
  3. With reshape(len(num_arr), -1), we reshape the combinations into a 2D Numpy array. As a result, due to the peculiar arrangement of values in the array (see step 1), we get a 5×6 Numpy array, where each column holds one combination of values.
  4. As we (presumably) want each combination in a row of the resulting array instead, we transpose the result of step 3 with .T to get the final result: a 6×5 Numpy array, where each row holds one combination of values.

Leave a Comment