Dole Dole - 3 months ago 9
Python Question

Reading string as text in an equation

I want to be able to execute the following code:

import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=k


Which should return the same output as:

z=numpy.zeros(4)
for i in range(6):
z[i]=z[i-1]


If I execute the first code block, I get an expected error message:

File "<ipython-input-982-3ba4e617a74a>", line 1, in <module>
z[i]=(k)

ValueError: could not convert string to float: 'z[i-1]'


How can I pass the text from the string into the loop so that it functions as an equation, as if the characters from the string were typed by hand?

Answer

Other then eval which is highly discouraged in production code, You can just as easily define a function that returns a specific item based on the array and index:

def k(arr,idx):
    return arr[idx-1]
for i in range(len(b)):
    z[i]= k(z,i)

If this rule needs to be applied in various spots in your code then you can edit the one function to apply that logic in all the places it is needed.