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

如何移除嵌套列表中每个子列表首个字符串内的分数?

移除嵌套列表子列表首个字符串中的分数

给定嵌套列表:

test = [['6 / 24 hello','4 / 5 askdskjf'],['2 / 3 dentist']]

需要移除每个子列表首个字符串开头的分数(如6 / 24、2 / 3),得到目标结果:

[[' hello', '4 / 5 askdskjf'], [' dentist']]

你之前的代码逻辑错误:[x for x in test if re.sub(r'^\d{1} / \d{2}','', x[0])]是在过滤原列表元素,而非修改子列表内容,自然无法得到预期结果。

正确实现方式

方式一:生成新列表(推荐,不修改原数据)

用嵌套列表推导式,对每个子列表的第一个元素做正则替换,其余元素直接保留:

import re

test = [['6 / 24 hello','4 / 5 askdskjf'],['2 / 3 dentist']]
result = [
    [re.sub(r'^\d+ / \d+', '', sub_list[0])] + sub_list[1:]
    for sub_list in test
]
print(result)
  • 正则^\d+ / \d+匹配字符串开头的「数字 / 数字」格式,替换为空字符串,兼容一位或多位数字的分数(比如10 / 200也能处理)
  • [处理后的首元素] + sub_list[1:]拼接成新的子列表,保留其余元素不变

方式二:原地修改原列表

如果不需要保留原列表数据,可以直接遍历修改:

import re

test = [['6 / 24 hello','4 / 5 askdskjf'],['2 / 3 dentist']]
for sub_list in test:
    sub_list[0] = re.sub(r'^\d+ / \d+', '', sub_list[0])
print(test)

两种方法运行后都能得到目标输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:57:10