Python将字符串的一部分转换为F

2024-04-24 05:23:02 发布

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

我试图制作一个包含两个字符串的列表:

List=["Hight = 7.2", "baselength = 8.32"]

但是我在从字符串中提取数字时遇到了一个问题:

例如:

如果"Hight = 7.2",那么结果应该是:7.2

或者如果"Hight= 7.3232",那么结果应该是:7.3232


Tags: 字符串列表数字listhightbaselength
3条回答

最好使用字典来管理与值关联的标签,但是,如果您必须将每个label=value对作为列表中的条目,因为您可能正在从其他地方将其读入Python,则可以使用re模块从列表中的每个字符串中提取数值:

import re
list=["height = 7.2", "length = 8.32"]
for dim in list:
    print(float(re.search('\d+.\d+', dim).group()))

使用^{}

>>> out = []
>>> for s in l: 
        out.append( float(re.findall('\d+(?:\.\d+)?', s)[0]) ) 

>>> out
=> [7.2, 8.0]

或者,不使用regex,使用split

>>> out = []
>>> for s in l:
        num = s.replace(' ','').split('=')[1]    
        #note : removed whitespace so don't have to deal with cases like
        #        `n = 2` or `n=2`
        out.append(float(num)) 

>>> out
=> [7.2, 8.0]

#驱动程序值:

IN : l = ["Hight = 7.2","baselength = 8"]

这个怎么样

[(item.split('=')[0],float(item.split('=')[1]) ) for item in List]

输出:

[('Hight ', 7.2), ('baselength ', 8.32)]

相关问题 更多 >