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

Python实现列表循环处理:提取目标子串并替换指定元素

Python列表元素批量处理解决方案

问题场景

给定如下列表:

test = ["Similar to Stxbp2: Syntaxin-binding protein 2 (Mus musculus)", "Protein of unknown function", "Similar to rab18b: Ras-related protein Rab-18-B (Danio rerio)", "Protein of unknown function", "Protein of unknown function"]

需要完成两类元素的批量修改:

  • 对以Similar to开头的元素,提取从第12个字符到冒号:之间的基因名称(如Stxbp2、rab18b)进行替换
  • 对内容为Protein of unknown function的元素,替换为Unknown

最终期望输出:

["Stxbp2", "Unknown", "rab18b", "Unknown", "Unknown"]

实现步骤

  1. 初始化一个空列表,用来存储处理后的结果
  2. 用for循环遍历原列表的每一个元素
  3. 针对每个元素做条件判断:
    • 若元素以Similar to开头,从索引12的位置开始截取,直到第一个冒号:出现的位置,把截取到的内容加入结果列表
    • 若元素完全匹配Protein of unknown function,直接把Unknown加入结果列表

完整代码示例

test = ["Similar to Stxbp2: Syntaxin-binding protein 2 (Mus musculus)", "Protein of unknown function", "Similar to rab18b: Ras-related protein Rab-18-B (Danio rerio)", "Protein of unknown function", "Protein of unknown function"]
result = []
for item in test:
    if item.startswith("Similar to"):
        # 从第12位截取到第一个冒号的位置
        gene_name = item[12:item.index(":")]
        result.append(gene_name)
    elif item == "Protein of unknown function":
        result.append("Unknown")
print(result)

代码说明

  • startswith("Similar to"):精准判断元素是否以指定字符串开头,避免误匹配
  • item.index(":"):返回字符串中第一个冒号的索引位置,结合起始索引12,能精准提取目标基因名称
  • 遍历过程中逐个处理元素并添加到结果列表,最终得到符合要求的新列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:20:35