Home > Mobile >  Create multiple array depending on a variable
Create multiple array depending on a variable

Time:10-04

I would like to create in Python multiple arrays whose names depend on a variable j, like this:

for j in range(30):
    x_j = np.loadtxt(f'Fid{j}.txt','r', unpack = True)
   

and the result would be to create 30 arrays x0, x1 .... x29. (Of course this code won't work).

I cannot make a matrix because each of this txt files has a different length, and I don't want to fill them with zeros because it would change a lot.

Do you have some ideas?

CodePudding user response:

You can use a dictionary where the key is j and value is the array itself

CodePudding user response:

Maybe it helps you to ask yourself, why you would want to create 30 independent variables for 30 different arrays in the first place?

Creating a dictionary with j as the key variable probably is the better way.

E.g.

x = dict()
for j in range(30):
   x[j] = np.loadtxt(f'Fid{j}.txt','r', unpack = True)

You can then acess each of these arrays easily by the "variables" x[0], x[17], or x[29] wherever you need to access them later in your code.

  • Related