【问题标题】:Python counting nucleotides with a for loopPython用for循环计算核苷酸
【发布时间】:2013-04-01 04:14:01
【问题描述】:

我正在尝试从输入文件中获取 DNA 序列,并使用循环计算单个 A 的 T、C 和 G 的数量,如果有非“ATCG”字母,我需要打印“错误”例如我的输入文件是:

序列1 AAAGCGT 序列2 aa tGcGt t 序列3 af GtgA cCTg

我想出的代码是:

acount = 0
ccount = 0
gcount = 0
tcount = 0
for line in input:
         line=line.strip('\n')
         if line[0] == ">":
                print line + "\n"
                output.write(line+"\n")
         else:
                line=line.upper()
                list=line.split()
                for list in line:

                        if list == "A":
                                acount = acount +
                                #print acount
                        elif list == "C":
                                ccount = ccount +
                                #print ccount 

                        elif list == "T":
                                tcount = tcount +
                                #print tcount 
                        elif list == "G":
                                gcount=gcount +1
                                #print gcount 
                        elif list != 'A'or 'T' or 'G' or 'C':
                                break

所以我需要得到每一行的总数,但我的代码给了我整个文件的 A 和 T 等的总数。我希望我的输出类似于

序列 1: 总 A:3 总C: 以此类推。

关于我可以做些什么来修复我的代码以实现这一点的任何想法?

【问题讨论】:

  • 在每个 for 循环迭代开始时重置 acount

标签: loops count dna-sequence


【解决方案1】:

我会建议以下几点:

import re

def countNucleotides(filePath):
    aCount = []
    gCount = []
    cCount = []
    tCount = []
    with open(filePath, 'rb') as data:
        for line in data:
            if not re.match(r'[agctAGCT]+',line):
                break
            aCount.append(notCount(line,'a'))
            gCount.append(notCount(line,'g'))
            cCount.append(notCount(line,'c'))
            tCount.append(notCount(line,'t'))

def notCount(line, character):
    appearances = 0
    for item in line:
        if item == character:
            appearances += 1
    return appearances

之后您可以随意打印它们。

【讨论】:

  • 我喜欢你在这里得到的@Slater Tyranus 唯一的问题是(如果你不知道的话)这是学校的作业,如果我使用 .count 函数,我会得到扣分。
  • 如果问题是作业,请使用作业标签。 Stack Overflow 不是真正的家庭作业,但我会更新问题以不使用计数功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 2017-09-29
  • 2022-01-10
相关资源
最近更新 更多