使用正则表达式从线性函数中提取系数

2024-09-27 21:32:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个功能

x1+3X2+2x3-2.2X4+19X5

我需要使用正则表达式提取系数[1,3,2,-2.2,19]

我做了[^x][1-9],但它不是一般性的。例如,如果我有

3x2-2.2x41+19x50

它将得到[3,-2.2,41,19,50],而不是[3,-2.2,19]

然后我需要一些东西来处理这个问题,比如[^x[1-9][1-9]],但是如果我有x124或x12345或 x后面有n个数字

我怎样才能排除它们而只得到系数呢


Tags: 功能数字x1系数x4x41x124x12345
1条回答
网友
1楼 · 发布于 2024-09-27 21:32:16
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]

相关问题 更多 >

    热门问题