You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从嵌套字符串列表中提取括号内的浮点数?

提取括号内内容并转换为浮点数列表

给定输入数据:

[['1. (25, 32)'], ['2. (24.2, 31.5)'], ['3. (22, 34)'], ['4. (20.5, 34)']]

需要提取每个字符串中括号内的数值,转换为浮点数后组成嵌套列表,期望输出:

[[25, 32], [24.2, 31.5], [22, 34], [20.5, 34]]

解决方案

方法1:正则表达式实现

正则表达式可精准匹配括号内的内容,适配格式稍有变化的场景:

import re

input_data = [['1. (25, 32)'], ['2. (24.2, 31.5)'], ['3. (22, 34)'], ['4. (20.5, 34)']]
result = [[float(num.strip()) for num in re.search(r'\((.*?)\)', item[0]).group(1).split(',')] for item in input_data]

print(result)

方法2:字符串索引实现

如果输入格式固定(每个字符串仅含一对括号),可直接通过索引定位括号位置:

input_data = [['1. (25, 32)'], ['2. (24.2, 31.5)'], ['3. (22, 34)'], ['4. (20.5, 34)']]
result = []
for item in input_data:
    s = item[0]
    # 定位括号的起始和结束位置
    start_idx = s.find('(') + 1
    end_idx = s.find(')')
    # 提取括号内的字符串并分割
    num_strings = s[start_idx:end_idx].split(',')
    # 转换为浮点数并添加到结果列表
    result.append([float(num.strip()) for num in num_strings])

print(result)

步骤说明

  1. 遍历输入的每个子列表,取出其中的单个字符串元素;
  2. 提取字符串中括号包裹的内容;
  3. 将提取到的内容按逗号分割为单个数字字符串,去除首尾空格后转换为浮点数;
  4. 将每组浮点数组成子列表,收集到最终结果中。

内容的提问来源于stack exchange,提问作者Elias El Haddad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:15:41