我试图从线方程“ ax + by + c”中获得系数a,b,c,而不使用NumPy或任何库。我尝试了字符串解析,但未成功,请帮助我,我是python的新手。
我假设您要解析一个包含数字a,b和c的字符串,那么下面的python示例向您展示了如何执行此操作:
import re
p = re.compile('([\d*\.\d+|\d+]+)x\+([\d*\.\d+|\d+]+)y\+([\d*\.\d+|\d+]+)')
m = p.match("1.2x+3y+4.5")
print("a=%s" % m.group(1))
print("b=%s" % m.group(2))
print("c=%s" % m.group(3))
或不使用正则表达式:
e = "1.2x-3y+4.5"
p=['']
for c in e: # loop through all characters
if c in ['.', '-'] or c.isdigit(): # if it's dot, minus or digit append it to the last parameter
p[len(p) - 1] += c
else: # otherwise create a new parameter
if len(p[len(p) - 1]) != 0: # when there isn't one yet
p.append('') # append new parameter
print("a=%s" % p[0])
print("b=%s" % p[1])
print("c=%s" % p[2])