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()
CodePudding user response:
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]
CodePudding user response:
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...