问题
Suppose I have some expression
from sympy import *
a,b,c,x,y = symbols('a c b x y')
eq=a*x + b*x*y + c*y**2
that needs to be split into an array containing the monomials.
The current solution I have is
parts = str(eq).split(' + ')
Then, I use the eval function on each element of the array parts to be interpreted as an expression.
What could I do to split the multivariate polynomial into the monomial parts without first converting the expression to a string?
回答1:
You can explore a sympy expression using .func and .args:
eq.func
> <class 'sympy.core.add.Add'>
eq.args
> (a*x, b*y**2, c*x*y)
Each of these args are again sympy expressions and can be explored in the same way:
eq.args[0].func
> <class 'sympy.core.mul.Mul'
eq.args[0].args
> (a, x)
And so on. Note that at the final levels of the expression tree you will need other functions than .func and .args, for example:
eq.args[0].args[0].name # the a in a*x
> 'a'
eq.args[1].args[1].args[1].n() # the 2 in y**2
> 2.00000000000000
来源:https://stackoverflow.com/questions/45126448/how-to-split-a-sum-into-its-parts-without-converting-to-string-in-python