我有一个包含字符串的列表:list = ['string', 'string', 'string', ...]
这些字符串类似于:'NumberDescription 33.3'
我只想提取没有 'NumberDescription' 部分的数字。
我已经尝试使用正则表达式和使用 re.match 的过滤函数。但这会导致一个空列表。
dat_re = re.compile(r'\d+.\d')
dat_list = list(filter(dat_re.match, list))
正如我所说,我只想要列表中的数字,在最后一步中,我想将列表的元素转换为 float 。
这里有几点:
- 自
re.match
only searches for the match at the string start起使用re.search
,
- 转义点,因为它是 special regex metacharacter
- 您仅使用
filter(...)
过滤列表,您不提取值。
- 如果您打算找到第一次出现的
digit+.digit+
,您可以使用正则表达式,例如 \d+\.\d+
- 如果您的项目都是
string number
格式使用s.split()[-1]
来获取数字,不需要正则表达式
使用
dat_list = [float(dat_re.search(x).group()) for x in l if dat_re.search(x)]
或者,如果格式是固定的
dat_list = [float(x.split()[-1]) for x in l]
参见 Python demo :
import re
l = ['string 23.3', 'NumberDescription 33.35']
dat_re = re.compile(r'\d+\.\d+')
dat_list = [float(dat_re.search(x).group()) for x in l if dat_re.search(x)]
print(dat_list)
# => [23.3, 33.35]
print([float(x.split()[-1]) for x in l])
# => [23.3, 33.35]
我是一名优秀的程序员,十分优秀!