【发布时间】:2020-01-26 13:28:33
【问题描述】:
我有一个包含字符串的列表:list = ['string', 'string', 'string', ...]
这些字符串就像:'NumberDescription 33.3'
我只想提取没有'NumberDescription' part.的数字
我已经尝试过使用正则表达式和使用 re.match 的过滤器功能。 但这会导致一个空列表。
dat_re = re.compile(r'\d+.\d')
dat_list = list(filter(dat_re.match, list))
正如我所说,我只想要列表中的数字,在最后一步中,我想将列表中的元素转换为浮点数。
【问题讨论】:
-
1) 使用
re.search, 2) 转义点 -
所以
dat_re = re.compile(r'\d+\.\d')和dat_list = list(filter(dat_re.search, list))?不工作。搜索返回初始列表。 -
但是您只过滤列表,不提取值。
dat_list = [dat_re.search(x).group() for x in l if dat_re.search(x)]
标签: python regex python-3.x list