0

I am trying to create arrays of fixed size within a while loop. Since I do not know how many arrays I have to create, I am using a loop to initiate them within a while loop. The problem I am facing is, with the array declaration.I would like the name of each array to end with the index of the while loop, so it will be later useful for my calculations. I do not expect to find a easy way out, however it would be great if someone can point me in the right direction

I tried using arrayname + str(i). This returns the error 'Can't assign to operator'.

#parse through the Load vector sheet to load the values of the stress  vector into the dataframe
Loadvector = x2.parse('Load_vector')

Lvec_rows = len(Loadvector.index)
Lvec_cols = len(Loadvector.columns)

i = 0
while i < Lvec_cols:
    y_values + str(i) = np.zeros(Lvec_rows)
    i = i +1 

I expect arrays with names arrayname1, arrayname2 ... to be created.

Vignesh S
  • 15
  • 4
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – Yassine Faris Jul 05 '19 at 09:02

1 Answers1

2

I think the title is somewhat misleading.

An easy way to do this would be using a dictionary:

dict_of_array = {}
i = 0
while i < Lvec_cols:
    dict_of_array[y_values + str(i)] = np.zeros(Lvec_rows)
    i = i +1 

and you can access arrayname1 by dict_of_array[arrayname1].

If you want to create a batch of arrays, try:

i = 0
while i < Lvec_cols:
    exec('{}{} = np.zeros(Lvec_rows)'.format(y_values, i))
    i = i +1 
Joseph Lee
  • 116
  • 1
  • 4
  • Thanks for your answer. But I get the error 'y_values ' is not defined for both the solutions you suggested. Does this mean , I have to declare y_values before the loop ? – Vignesh S Jul 05 '19 at 09:36
  • Sure you are. I just use the variable name you provided. Maybe `'arrayname'`? – Joseph Lee Jul 05 '19 at 09:43
  • Using a dictionary is the way to go here, so just define a basename basename = 'array_' and then in the while loop dict_of_array[basename + str(i)] = np.zeros(Lvec_rows) – David Montgomery Jul 05 '19 at 09:46