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

如何使用Python移除列表特殊字符并转换为规范二维列表

问题描述

现有存在冗余转义字符、多余前缀的列表结构,原始定义如下:

z=[']\'What type of humans arrived on the Indian subcontinent from Africa?\', \'When did humans first arrive on the Indian subcontinent?\', \'What subcontinent did humans first arrive on?\', \'Between 73000 and what year ago did humans first arrive on the Indian subcontinent?',\kingdoms were established in Southeast Asia?Indianized\']']

需要将其清理为规范的二维列表,目标效果如下:

z= [['What type of humans arrived on the Indian subcontinent from Africa?', 'When did humans first arrive on the Indian subcontinent?', 'What subcontinent did humans first arrive on?', 'Between 73000 and what year ago did humans first arrive on the Indian subcontinent?','kingdoms were established in Southeast Asia?Indianized']]
实现代码

直接通过字符串预处理+拆分即可完成转换,可直接运行的代码如下:

# 原始待处理列表
z = [']\'What type of humans arrived on the Indian subcontinent from Africa?\', \'When did humans first arrive on the Indian subcontinent?\', \'What subcontinent did humans first arrive on?\', \'Between 73000 and what year ago did humans first arrive on the Indian subcontinent?',\\'kingdoms were established in Southeast Asia?Indianized\'']']

# 取出内层字符串,清理冗余字符
raw_content = z[0]
# 移除开头多余的]'前缀,替换所有多余的转义反斜杠
clean_content = raw_content.lstrip("]'").replace("\\", "")
# 按固定分隔符拆分每个问题项,去除首尾残留的单引号
question_list = [item.strip("'") for item in clean_content.split("', '")]
# 组装为目标二维列表
z = [question_list]
逻辑说明
  • 原始列表的唯一元素是一整个拼接错误的字符串,所有冗余的特殊字符都在这个字符串内
  • lstrip("]'")用于清除字符串开头多余的右括号和单引号前缀
  • 替换反斜杠操作可以移除所有错误添加的转义符,还原正常的文本内容
  • 按照问题项之间固定的分隔符', '拆分字符串,即可得到每个独立的问题文本
  • 最后将拆分好的问题列表嵌套一层列表,就得到符合要求的二维列表结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 00:12:41