1

I have an array (oned_2018) and I want a function to make multiple copies of this array. The number of copies is the largest value in this array. e.g. largest is 6; then there should be 6 copies. Could anyone please help me write this loop? I want something like...

for i in range(1, max(oned_2018)+1):
    classi_20 = oned_2018.copy() # of course this line is incorrect!

and outputs should be like this manual work:

class1_20 = oned_2018.copy()

class2_20 = oned_2018.copy()

class3_20 = oned_2018.copy()

class4_20 = oned_2018.copy()

class5_20 = oned_2018.copy()

class6_20 = oned_2018.copy()
GeoSn0w
  • 684
  • 1
  • 9
  • 20

2 Answers2

0

If you really want to to so, you can use globals():

oned_2018 = [1, 2, 3, 4]
for i in range(1, max(oned_2018)+1):
    globals()[f"class{i}_20"] = oned_2018.copy() # of course this line is incorrect!

print(class1_20) # [1, 2, 3, 4]

But dynamically creating variables like this is generally avoided. Usually people would recommend using dict instead:

oned_2018 = [1, 2, 3, 4]
data = {f"class{i+1}_20": oned_2018.copy() for i in range(max(oned_2018))}

print(data['class1_20']) # [1, 2, 3, 4]
j1-lee
  • 13,764
  • 3
  • 14
  • 26
  • Hi, @j1-lee, may I have a question for you? If globals() means that the outputs exist in global environment, should I use something like locals() if I eventually wrap this copying function into a bigger function? Thanks!! – Claire Wang Oct 25 '21 at 19:57
  • @ClaireWang Unfortunately, I don't think that is possible or at least easy: https://stackoverflow.com/questions/1450275/any-way-to-modify-locals-dictionary – j1-lee Oct 25 '21 at 20:54
0

Instead of naming them by variable, I would suggest you to use a dictionary as such:

classes_to_data = {}
for i in range(1, max(oned_2018)+1):
    classes_to_data[i] = oned_2018.copy()

Then, you can access them as follows:

classes_to_data[1]  # outputs what you named 'class1_20'
classes_to_data[2]  # outputs what you named 'class2_20'
# and so on...
fmigneault
  • 341
  • 3
  • 5
  • Thanks for the input but I need the results to be individual arrays as my next steps are changing values and exporting as images :) – Claire Wang Oct 23 '21 at 20:21
  • You can do exactly that with this method. Update your values as follows: `classes_to_data[1][0, 0] = 1 # set 1 to first array at index (0, 0)` `classes_to_data[1].save("file.npy") # save first array to file` Each `classes_to_data[i]` will be a distinct array that you can manipulate however you desire. – fmigneault Oct 28 '21 at 03:47