如何使内循环考虑外循环的每次迭代?

2024-04-26 21:53:42 发布

您现在位置:Python中文网/ 问答频道 /正文

'A', 'U', 'G' or 'C'组成的三字母组被定义为密码子。每个密码子对应20个字母中的一个。这组字母(氨基酸)被定义为蛋白质。“文件”密码子.txt包含密码子和相应的字母。你知道吗

下一个问题是:内部for循环只工作一次—它只将txt文件中的行与第一个密码子进行比较。然后,据我所知,该方法跳过了内部循环。你知道吗

代码:

path = r'C:\Users\...\codons.txt'
f = open(path, 'r')

def prot(DNA):
    protein = ''
    a = True
    for i in range (0, len(DNA)-2,3):
        codon = DNA[i:i+3:1]
        print(codon)
        for line in f:
            if line[0:3:1] == codon:
                protein += line[4:5:1]
                print(protein)
    return protein


prot('AGUCAGGAUAGUCUUA')

输出:

 AGU
 S
 CAG
 GAU
 AGU
 CUU

接下来的问题是:如何使每个密码子的内环工作?你知道吗


Tags: 文件pathintxtfor定义字母line
1条回答
网友
1楼 · 发布于 2024-04-26 21:53:42

在文件(for line in f:)上迭代时,到达文件末尾时停止。你知道吗

您可以:

  • 使用^{}将文件读取器位置重置为文件开头
  • 或者更改循环的顺序,以便只在文件上迭代一次。你知道吗

    def prot(DNA):
        protein = ''
    
        with open(path, 'r') as f:
            for line in f:
                for i in range (0, len(DNA)-2,3):
                    codon = DNA[i:i+3:1]
                    print(codon)
    
                        if line[0:3:1] == codon:
                            protein += line[4:5:1]
                            print(protein)
    
        return protein
    

相关问题 更多 >