python - 我想从带有字符串的列表中提取数字

标签 python regex python-3.x list

我有一个包含字符串的列表: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 。

最佳答案

这里有几点:

  1. re.match only searches for the match at the string start 起使用 re.search ,
  2. 转义点,因为它是 special regex metacharacter
  3. 仅使用 filter(...) 过滤列表,而不提取值。
  4. 如果您打算查找 digit+.digit+ 第一次出现,您可以使用正则表达式,例如 \d+\.\d+
  5. 如果您的项目全部采用字符串数字格式,请使用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]

关于python - 我想从带有字符串的列表中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58113903/

相关文章:

python - 将数据框转换为字典

Python正则表达式查找不完整的左括号和右括号

javascript - 不带正则表达式的字母数字验证 javascript 2

python - argparse 可选子解析器(用于 --version)

python - 正确移动 Pandas 中的不规则时间序列

python Pandas : instancemethod object is not iterable

regex - Apache mod 重写在 mac 上自动添加文件扩展名

python - cx_Oracle连接速度慢

python-3.x - 更改 hvplot.hist 的默认悬停数据

python - 将列表的每个元素写在 Python 文本文件的换行符上