-2

I have a function which creates a set of results in a list. This is in a for-loop which changes one of the variables in each iteration. I need to be able to store these lists separately so that I can show the difference in results between each iteration as a graph.

Is there any way to store them separately like that? So far the only solution I've found is to copy out the function multiple times and manually change the variable and name of the list it stores to, but obviously this is a terrible way of doing it and I figure there must be a proper way.

Here is the code. The function is messy but works. Ideally I would be able to put this all in another for-loop which changes deceleration_p each iteration and then stores collected_averages as a different list so that I could compare collected_averages for each iteration.

import numpy as np
import random
import matplotlib.pyplot as plt
from statistics import mean

road_length = 500
deceleration_p = 0.1
max_speed = 5
buffer_road = np.zeros(road_length, dtype=int)
buffer_speed = 0
number_of_iterations = 1000
average_speed = 0
average_speed_list = []
collected_averages = []
total_speed = 0

for cars in range(1, road_length):
    empty_road = np.ones(road_length - cars, dtype=int) * -1
    cars_on_road = np.ones(cars, dtype=int)
    road = np.append(empty_road, cars_on_road)
    np.random.shuffle(road)
    for i in range(0, number_of_iterations):
        # acceleration
        for speed in np.nditer(road, op_flags=['readwrite']):
            if -1 < speed < max_speed:
                speed[...] += 1
        # randomisation
        for speed in np.nditer(road, op_flags=['readwrite']):
            if 0 < speed:
                if deceleration_p > random.random():
                    speed += -1
        # slowing down
        for cell in range(0, road_length):
            speed = road[cell]
            for val in range(1, speed + 1):
                new_speed = val
                if (cell + val) > (road_length - 1):
                    val += -road_length
                if road[cell + val] > -1:
                    speed = val - 1
                    road[cell] = new_speed - 1
                    break
        buffer_road=np.ones(road_length, dtype=int)*-1
        for cell in range(0, road_length):
            speed = road[cell]
            buffer_cell = cell + speed
            if (buffer_cell) > (road_length - 1):
                buffer_cell += -road_length
            if speed > -1:
                total_speed += speed
                buffer_road[buffer_cell] = speed
        road = buffer_road
        average_speed = total_speed/cars
        average_speed_list.append(average_speed)
        average_speed = 0
        total_speed = 0
    steady_state_average=mean(average_speed_list[9:number_of_iterations])
    average_speed_list=[]
    collected_averages.append(steady_state_average)
martineau
  • 119,623
  • 25
  • 170
  • 301
Jim_tal
  • 1
  • 1
  • 4
    Hi, could you include the code in your post? – Badgy Apr 07 '20 at 16:20
  • Why not save them into a dictionary? `{'foo': [...], 'bar': [...]}` then later you can look up the list corresponding to each variable you passed – Cory Kramer Apr 07 '20 at 16:21
  • Hello! Welcome to StackOverflow! Please provide your code for more help on the matter, since StackOverflow mostly works on this principle! However, I would advise using a list of lists for this specific task. – peki Apr 07 '20 at 16:21
  • 1
    The answer to "can I create new named variables in a loop" is yes. Is it the right thing to do? Only about 0.0001% of the time. Instead, use a container like a list, appending the result of each loop to the end, or a dictionary with meaningful key names. – SyntaxVoid Apr 07 '20 at 16:24
  • Make the variable a list-of-arrays and append an array of results to it each iteration. Generally you don't want to create variables on-the-fly — see [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – martineau Apr 07 '20 at 17:08

1 Answers1

0

Not to my knowledge. As stated in the comments, you could use a dictionary, but my suggestion is to use a list. For every iteration of the loop, you could append the value. (From what I understood) You stated that your results are in a list, so you could make a 2D array. My recommendation would be to use a numpy array as it is much faster. Hopefully this was helpful.

Cerumersi
  • 77
  • 10