Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python SyntaxError: cannot assign to operator – Defining variables as sum of strings in for loop

I’m trying to condense some repetitive code by setting up a for loop to define variable names. I get that python doesn’t like having operators on the left side of equations, but are there any workarounds for adding strings together for the sake of defining a variable name that will later be referenced?

cases     = ['case1','case2', 'case3']
condition = ['con1', 'con2']
var       = ['var1', 'var2', 'var3']
for i in cases :
    for j in condition :
        for k in var :
            filename = i+j+k+'.txt'
            i+j+k = np.loadtxt(filename)
            plt.plot(x, i+j+k)
plt.show

I’m thinking my best option would option would be set up a matrix in the loop as

value[i,j,k] = np.loadtxt(filename)
plt.plot(x, value[i,j,k])

but that might lead to bigger headaches in the future so I’m trying to avoid if possible.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Creating variable names based on strings is not allowed. Using a dictionary to store the values with your custom string is the closest thing you will get.

Also, you have a mistake here: filename = i+j+k'.txt' , you need to add the .txt string to the other strings like this filename = i+j+k+'.txt'

cases     = ['case1','case2', 'case3']
condition = ['con1', 'con2']
var       = ['var1', 'var2', 'var3']
case_condition_variables = dict()

for i in cases :
    for j in condition :
        for k in var :
            filename = i+j+k+'.txt'
            case_condition_variables[i+j+k] = np.loadtxt(filename)
            plt.plot(x, case_condition_variables[i+j+k])

print(case_condition_variables) # will show you all the name - value pairs
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading