简体   繁体   中英

Parsing a list and create expressions

I have a list of strings:

A = ['a','b']

I want to parse this list and write following expressions:

a = x**2
b = a*x

where x is a sympy symbol and later on I will use these expressions for other operations like differentiation and so on. The problem is that a and b are strings inside the list. I am not being able to use them as expressions! How can I do this?

In general, you don't. Trying to set up dynamic variable names is usually a sign of poor design. If you do need those symbols to represent things to the outside world, try keeping a label and a value. For instance, a dictionary can do something like this for you.

symbol = { 'a': x**2; 'b': x**3 }

You can add symbols from there, change values, etc. For instance,

symbol = { 'a': x**2 }
symbol['b'] = symbol['a'] * x

Granted, you can build an expression string and use eval on the contents, but this is generally dangerous and hard to maintain well.

A wider possibility is to manipulate string values and write the Python script you'd like to run. Write it to a file and then use the os or subprocess commands to execute it.

Does that get you moving?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM