错误来自最后一个数字的最后一行-1.3147E+
。这不是正确的表示法,后面的索引E
不见了。
一种解决方案可能是在应用步骤之前将其替换为:
poly = re.sub(r"(E\+)$", '', poly)
代码变为:
pattern = r'([\+\-]?\d+\.?\d+[Ee]?[\+\-]?\d*)[x\^\d+]?|([\+\-]?\d+\.?\d*[Ee]?[\+\-]?\d*)x'
for poly in polys:
poly = re.sub(r"(E\+)$", '', poly)
coeffs = []
for match in re.finditer(pattern, poly):
groups = match.groups()
coeff = groups[0] if groups[0] is not None else groups[1]
coeffs.append(float(coeff))
print(coeffs)
# [1.0]
# [3.8546e-27, -2.4333e-20, 5.1165e-14, 3.7718e-06, -0.61561]
# [0.00613159, 0.348]
# [0.0100708, -40.0]
# [0.006103516]
# [1e-06]
# [1.4846859e-06]
# [2435.0]
# [2.7883e-27, -2.2164e-20, 5.8443e-14, 7.5773e-06, -1.3147]
这是另一种方法split
:
out = []
for poly in polys:
poly = re.sub(r"(E\+)$", '', poly)
list_coef = re.split(r'x[\^\d]*', poly)
list_coef = [float(elt) for elt in list_coef if elt]
out.append(list_coef)
[print(o) for o in out]
# [1.0]
# [3.8546e-27, -2.4333e-20, 5.1165e-14, 3.7718e-06, -0.61561]
# [0.00613159, 0.348]
# [0.0100708, -40.0]
# [0.006103516]
# [1e-06]
# [1.4846859e-06]
# [2435.0]
# [2.7883e-27, -2.2164e-20, 5.8443e-14, 7.5773e-06, -1.3147]