简体   繁体   中英

extracting numbers from a string in a list via regex

I've a linear equation and i'm trying to process it in Python . This linear equation is in a list.

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)']

I want to find a way to build a list which contains all the constants.

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

will give you a list m :

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

If you want the list as a list of floating point numbers, you can now do:

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

If you want to extract the constants in a list, the following should do the work:

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

This will output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM