0

I have a block of code that I am trying to scale up. The code works great for my application, but I need a more elegant and efficient way to scale this up so that I don't have to manually write hundreds of lines. Essentially, I am creating a set of empty lists for each location I am modeling, identifying all of the locations from a model, then running a simulation to update the empty lists with values for each location, and finally plotting the update list for each location. This works great, but instead of only having three locations, C1, C2, and C3, I would like to do this for hundreds. I have poked around and messed with the code, but can't find a way to automate this with a loop or other approach. I would like to automate each step where you can see repetition, which is step 1, 2, 3, and 5.

### 1.  Create empty lists
C1_p = []
C2_p = []
C3_p = []

### 2.  Identify Locations
with Simulation('Generic_File_Name.file') as sim:
    X = testing(sim,config)
    C1 = Links(sim)['C1']
    C2 = Links(sim)['C2']
    C3 = Links(sim)['C3']
### 3.  Update empty lists with new values from simulation   
    for step in sim:
        X.updateXState()
        C1_p.append(C1.concentration['Solid_W'])
        C2_p.append(C2.concentration['Solid_W'])
        C3_p.append(C3.concentration['Solid_W'])

### 4.  Create x-values for plot
start = 0.0
stop = len(C1_p)
interval = 1
t = np.arange(start, stop , interval)


### 5.  Plot data
plt.plot(t, C1_p, label='C1')
plt.plot(t, C2_p, label='C2')
plt.plot(t, C3_p, label='C3')
plt.legend()
plt.show()

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    Use dictionaries, where your "C*_p" are your keys in the dictionary and the value is the list. – Shmack Feb 15 '23 at 19:23
  • Does either [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) or [How can you dynamically create variables?](https://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables) answer your question? – wwii Feb 15 '23 at 19:24
  • Use string formatting and enumerate to make the keys. – wwii Feb 15 '23 at 19:28

0 Answers0