我有这个功能
x1+3 x2+2 x3-2.2 x4+19 x5
我需要使用正则表达式提取系数[1,3,2,-2.2,19]
我做了[^x][1-9],但不是一般性的。例如,如果我有
3 x2-2.2 x41+19 x50
它将得到[3,-2.2,41,19,50]而不是[3,-22.19]
然后我需要一些东西来处理这个问题,比如[^x[1-9][1-9],但如果我有x124或x12345或x之后的n位数字。
我怎么能把它们排除在外,只得到系数呢?
import re
# define the problem
mystring='x1 +3 x2 +2 x3 -2.2 x4 +19 x5'
# get coefficients
regex_coeff='([+-]d*.{0,1}d+) x'
# assuming your polynome is normalized, we can add the one in front
coeffs=[1.0] + [float(x) for x in re.findall(regex_coeff,mystring)]
# get exponents
regex_expo='x(d+)'
exponents=[int(x) for x in re.findall(regex_expo,mystring)]
# print results
print(coeffs)
print(exponents)
>>[1.0, 3.0, 2.0, -2.2, 19.0]
>>[1, 2, 3, 4, 5]