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

如何从带括号、百分比的列表项中提取数字生成新列表并批量处理

字符串数组数字提取及批量处理方案

核心规则说明

你给出的样本数据满足两个特征:

  • 列表第一个元素为无效值T,直接跳过即可
  • 其余有效元素要么是纯数字字符串,要么是数字(百分比)格式,只需要提取括号前的数字转为整数即可

单个数组处理实现

不需要复杂逻辑,直接按(分割字符串取首部即可,示例代码如下:

# 原始数组
x = ['T','0(99%)','2','0','8(56%)','0','0','0']

def process_single_list(input_list):
    result = []
    # 跳过第一个无效元素,遍历剩余内容
    for item in input_list[1:]:
        # 按(分割,取第一部分去除空格后转整数
        num = int(item.split('(')[0].strip())
        result.append(num)
    return result

# 测试调用
target = process_single_list(x)
print(target)
# 输出:[0, 2, 0, 8, 0, 0, 0]

如果你的数据还有其他格式干扰,比如括号前有非数字字符,可以用正则匹配提取开头的连续数字,适配性更强:

import re

def process_single_list(input_list):
    result = []
    for item in input_list[1:]:
        # 匹配字符串开头的连续数字
        num_match = re.match(r'\d+', item.strip())
        if num_match:
            result.append(int(num_match.group()))
    return result

多列表批量处理实现

把所有待处理的列表存入一个大的列表容器,循环调用处理函数即可,示例代码如下:

# 待处理的多个同类列表集合
batch_lists = [
    ['T','0(99%)','2','0','8(56%)','0','0','0'],
    ['T','3(87%)','5','1','2(33%)','0','1','0'],
    ['T','9(12%)','0','4','7(91%)','2','0','3']
]

# 存储批量处理结果
batch_results = []
for lst in batch_lists:
    processed = process_single_list(lst)
    batch_results.append(processed)

# 输出所有处理结果
for res in batch_results:
    print(res)

内容的提问来源于stack exchange,提问作者Pjose123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:24:03