我有以下代码读取包含 10 个基因序列的 FASTA 文件并将每个序列作为矩阵返回。 然而,代码似乎在最后一个序列中丢失了,我想知道为什么?
file=open('/Users/vivianspro/Downloads/rosalind_cons (5).txt', 'r')
line=file.readline()
strings = []
sequence=''
while line:
#line=line.rstrip('\n')
line = line.strip() #empty () automatically strips the \n
if '>' in line:
if sequence != "":
strings.append(sequence)
sequence = ""
#sequence=line
else:
sequence+=line
line=file.readline()
for s in strings:
print(s)
Motifs = []
for seq in strings:
Motifs.append(list(seq))
#make every symbol into an element in the list separated by ,
for s in Motifs:
print(s) ````
请您参考如下方法:
当您看到一个新的 > 但在最后一个序列之后没有一个时,您只追加到 strings。
这是一个重构,希望它也更符合惯用语。
strings = []
sequence=''
with open('/Users/vivianspro/Downloads/rosalind_cons (5).txt', 'r') as file:
for line in file:
line = line.rstrip('\n')
if line.startswith('>'):
if sequence != "":
strings.append(sequence)
sequence = ""
else:
sequence+=line
# After the last iteration, append once more if we have something to append
if sequence:
strings.append(sequence)
