gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:05 25 4
gpt4 key购买 nike

我有一个包含字符串的列表: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. 如果您的项目都是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]

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com