DNA序列中的GC含量(Rosaland):如何改进我的代码?

时间:2015-01-07 23:15:14

标签: python

以下是我在不使用Biopython的情况下计算GC内容的Rosalind问题的代码。 任何人都可以给我一些建议如何改进它?例如,我不能在for循环中的seq_list中包含最后一个序列,并且必须再添加一次。 另外,是否有更好的方法来配置seq_name和GC内容,以便我可以轻松打印出具有最高GC内容的序列名称? 非常感谢你

# to open FASTA format sequence file:
s=open('5_GC_content.txt','r').readlines()

# to create two lists, one for names, one for sequences
name_list=[]
seq_list=[]

data='' # to put the sequence from several lines together

for line in s:
    line=line.strip()
    for i in line:
        if i == '>':
            name_list.append(line[1:])
            if data:
                seq_list.append(data)
                data=''
            break
        else:
            line=line.upper()
    if all([k==k.upper() for k in line]):
        data=data+line
seq_list.append(data) # is there a way to include the last sequence in the for loop?
GC_list=[]
for seq in seq_list:
    i=0
    for k in seq:
        if k=="G" or k=='C':
            i+=1
    GC_cont=float(i)/len(seq)*100.0
    GC_list.append(GC_cont)


m=max(GC_list)
print name_list[GC_list.index(m)] # to find the index of max GC
print "{:0.6f}".format(m)

2 个答案:

答案 0 :(得分:0)

if all([k==k.upper() for k in line]):

为什么不检查line == line.upper()

i=0
for k in seq:
    if k=="G" or k=='C':
        i+=1

可以替换为     i = sum(如果在['G','C']中的k,则为seq中的k为1)

  

有没有办法在for循环中包含最后一个序列?

我认为没有更好的方法可以做到这一点。

答案 1 :(得分:0)

为避免第二次追加您的seq列表,请删除:

if all([k==k.upper() for k in line]):
    data=data+line

并将其添加到line.strip()

下方

您遇到的问题是,第一次进入for i in line循环时,数据是一个空字符串。因此,if data:为假。