1

I am trying to write a code to iterate over columns in a datasheet and create variables depending on the number of columns. The variables will then be used in an optimization problem so I need the variables to not have any value assigned to them.

I created a list containing strings like list_w = ['w1', 'w2', ..... 'w35'] but I need these strings to act as variables.

This is what I tried to do based off some online resources but this doesn't work:

def objective(w):
    for e in list_w:
        f = list_w.index(e)
        vars()[e] =w[f]
        print(e)

    return w1*w2*w3*w4
ALollz
  • 57,915
  • 7
  • 66
  • 89
Ray234
  • 173
  • 5
  • 15
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – G. Anderson May 07 '19 at 19:46

1 Answers1

0

What you actually want is a dictionary:

def objective(w):
    my_dict = dict()
    for e in list_w:
        my_dict[e] = w[list_w.index(e)]
     return my_dict

Your values are now accessibe from each "variable" (dictionary key) like my_dict['w1']. To get the result of their multiplication, you can just loop over the values of your dictionary:

result = 1
for val in my_dict.values():
    result *= val

On the other hand, from your code it seems that all you need is the associated index of each element inside list_w (assuming each element is unique). If that's the case, take a look at enumerate.

jfaccioni
  • 7,099
  • 1
  • 9
  • 25
  • Using a dictionary will assign values to keys but I need a way to just declare the items in my list as variables and later use them in an optimization problem where the objective is to minimize the variance of a large data sheet. – Ray234 May 07 '19 at 20:30