通过正则表达式从列表中的字符串中提取数字

时间:2014-06-20 08:16:17

标签: python regex list

我是一个线性方程式,我试图在Python中处理它。这个线性方程式在列表中。

z=['i=(6040.66194238063)+(51.7296373326464*a)+(41.7319764455748*b)+(-193.993966414084*c)+(-215.670960526368*d)+(-531.841753178744*e)+(5047.1039987166*f)+(3925.37115184923*g)+(77.7712765761365*h)']

我想找到一种方法来构建一个包含所有常量的列表。

2 个答案:

答案 0 :(得分:2)

import re
m=re.findall('-?[0-9]+\.?[0-9]*', z[0])

会为您提供一个列表m

['6040.66194238063', '51.7296373326464', '41.7319764455748', '-193.993966414084', '-215.670960526368', '-531.841753178744', '5047.1039987166', '3925.37115184923', '77.7712765761365']

如果您希望列表作为浮点数列表,您现在可以执行以下操作:

m = [float(x) for x in m]

答案 1 :(得分:1)

如果要在列表中提取常量,则应执行以下操作:

z = ["i=(6040.66194238063)+(51.7296373326464*a)+(41.7319764455748*b)+(-193.993966414084*c)+(-215.670960526368*d)+(-531.841753178744*e)+(5047.1039987166*f)+(3925.37115184923*g)+(77.7712765761365*h)"]
for elem in z:
    num = ""
    cst = []
    for c in elem:
        if c.isdigit() or c =='.' or (c == '-' and not len(num)):
            num += c
        elif len(num):
            cst.append(num)
            num = ""
    print cst

这将输出:

['6040.66194238063', '51.7296373326464', '41.7319764455748', '193.993966414084', '215.670960526368', '531.841753178744', '5047.1039987166', '3925.37115184923', '77.7712765761365']