Need help declaring and assigning multidimensional arrays with different numbers of elements in Python (v Java)

Viewed 51

I am a long time java user diving into python.
I am searching for a way to create multi-dim arrays that may not have the same number of elements, some or all are NOT known until run time.

In java I'd assign a 3 dimensional array named runSet like this below:

double[][][] runSet = new double[5][][];

int randomInt = genRandInt();  // Returns a random integer between 0 and 101.

for(int i = 0; i < 4; i++) runSet[i] = getRuns(randomInt);  // Returns double[randomInt][ToBeDetermined]

// ------------------------------------------------------------------------------

public double[][] getRuns(int num)
{  
  double[][] array2D = new double[num][];
  for(int i = 0; i< num; i++) array2D[i] = genRandArray(); // returns double[] of random values with length between 0 and 1001.
  
  return array2D; // Returns double[num][Varying Length]
} // end GetRuns()

No problems, this works just fine. BUT using python I want to do the same, and I cannot figure out how to properly assign arrays with unknown number of elements. The best I have been able to come up with is:

import numpy as np
    
runSet = np.empty([5, ]) # <--- Does NOT throw an error.
randomInt = genRandInt()   # Returns a random integer between 0 and whatever.

i = 0
while i < 4:
   runSet[i] = getRuns(randomInt)  # Returns [][] (double[randomInt][ToBeDetermined] in java speak)
   i += 1

#-------------------------------------------------
    
def getRuns(num) 
    array2D = np.empty([num, ]) # <-- Does NOT throw an error.
    i = 0
    while i < num:
         array2D[i] = genRandArray(); # Returns double[] of random values with a random LENGTH as well.
         i += 1
          
    return array2D; // Returns double[num][Varying Length]
    
# end GetRuns()

In genRandArray(), python version, I am returning with this (example random) statement:

return [12.4, 6.4, 8.0, 7.9, 8.2, 6.3, 8.8, 3.14, 2.345, 66.828, 12.0]

In both places I assign runSet[i] & array2D[i], I now know I'll get the error kind of like "sequential list being added to single ...."

Question 1): Maybe an array form is better for the return?

Question 2): Am I even close?
I have the feeling I may be going about this the completely wrong way, as the array thinking in python seems totally bass akward from the way I've been trained to think about it in java. Thanks for any help!

0 Answers
Related