Dole Dole - 1 year ago 67
Python Question

Reading string as text in an equation

I want to be able to execute the following code:

import numpy
for i in range(len(b)):

Which should return the same output as:

for i in range(6):

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

File "<ipython-input-982-3ba4e617a74a>", line 1, in <module>

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download