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

如何调整Python代码实现氨基酸位点检测结果的横向排版输出

问题解决:修改Python代码实现每行输出三个氨基酸检测结果

问题分析

原代码将检测结果分别存入三个独立列表,最后仅循环输出v_list的元素,导致结果竖排显示。要实现每行输出对应序列的三个检测结果,需要将三个列表的对应元素配对后逐行打印。另外原代码存在两处细节问题:

  • 索引错误:你需要检测第234位氨基酸,但代码中取的是sequence[4](对应第5位),Python序列是0索引,正确索引应为sequence[233]
  • 拼写错误:amino_list中的Glutaminc Acid应为Glutamic Acid

修改后的代码

import re

# 假设fasta是已打开的文件对象
v_list = []
i_list = []
e_list = []
amino_list = 'Valine', 'Isoleucine', 'Glutamic Acid'
content = fasta.read()

# 打印表头
print('Valine' + '\t' + 'Isoleucine' + '\t' + 'Glutamic Acid')

for line in content.split(">"):
    if re.search(r"fibroblast growth factor receptor 1 isoform", line):
        # 清理序列(可根据实际FASTA格式调整正则)
        sequence = re.sub('NP.*]', '', line).strip()  # 去除多余空白字符
        # 修正索引并增加长度检查,避免索引越界报错
        if len(sequence) >= 234:
            amino = sequence[233]
        else:
            amino = ''
        
        # 检测结果存入列表
        v_list.append(1 if amino == 'V' else 0)
        i_list.append(1 if amino == 'I' else 0)
        e_list.append(1 if amino == 'E' else 0)

# 配对三个列表的对应元素,逐行打印结果
for v, i, e in zip(v_list, i_list, e_list):
    print(f"{v}\t{i}\t{e}")

关键修改点

  • 用zip(v_list, i_list, e_list)将三个列表的对应元素配对,实现每行输出一组检测结果
  • 修正了氨基酸位置的索引错误,并增加序列长度检查防止报错
  • 简化条件判断写法,让代码更简洁
  • 修正了Glutamic Acid的拼写错误

更简洁的实现(无需存储结果列表)

如果不需要保留检测结果的历史数据,可直接在处理每个序列时打印结果,节省内存:

import re

content = fasta.read()
print('Valine' + '\t' + 'Isoleucine' + '\t' + 'Glutamic Acid')

for line in content.split(">"):
    if re.search(r"fibroblast growth factor receptor 1 isoform", line):
        sequence = re.sub('NP.*]', '', line).strip()
        amino = sequence[233] if len(sequence) >=234 else ''
        v = 1 if amino == 'V' else 0
        i = 1 if amino == 'I' else 0
        e = 1 if amino == 'E' else 0
        print(f"{v}\t{i}\t{e}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 13:51:17