1

I'm wondering whether it is possible to select a variable based on a certain condition/input.

For example:

day_1 = 5
day_2 = 10
day_3 = 15
i =2
selected_variable = day_i

The code would give an error that of course day_i is not defined. I know I could add all variables to a list and access them through list locations etc but I'm working with a rather big Simpy environment in which this would be very useful if it exists.

Thanks!

Aimee Vis
  • 51
  • 2
  • 3

4 Answers4

2

You can use vars() to get all varables in the scope.

for exsample:

day_1 = 5
day_2 = 10
day_3 = 15
i = 2
selected_variable = vars()[f"day_{i}"]
xkcdjerry
  • 965
  • 4
  • 15
0

You can stores the values in a list, and use i as an index to access one box, you do i-1 because list are indexed from 0

days = [5, 10, 15]
i = 2
selected_variable = days[i - 1]

You can also associated key/value in a dictionary, and from a number get the value

days = {
    1: 5, 2: 10, 3: 15
}
i = 2
selected_variable = days[i]
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
azro
  • 53,056
  • 7
  • 34
  • 70
0

As mentioned in comments there are couple of sulutions:

You can define a dict:

day = {
"day_1": 5,
"day_2": = 10,
"day_3": = 15
}

selected_variable = day[f"day_{i}"]

An array

day = [
5,
10,
15
]

selected_variable = day[i] 

An If statement

day_1 = 5
day_2 = 10
day_3 = 15

if i == 1:
    selected_variable = day_1
elif i == 2:
    selected_variable = day_2
elif i == 3:
    selected_variable = day_3

Or the locals (or vars) dict (my favorite in this case)

day_1 = 5
day_2 = 10
day_3 = 15

selected_variable = locals()[f"day_{i}"]
majkrzak
  • 1,332
  • 3
  • 14
  • 30
0

The below code will print out the value of the variable day_2

i =2
selected_variable = 'day_{}'.format(str(i))
exec("print(%s)" % selected_variable)
Sanil
  • 369
  • 2
  • 7