我有多个fasta文件,其中包含多个具有相同长度序列的个体。我想要做的是创建一个沿着fasta文件的物种序列的连接。
在循环中:如果在下一个文件中找到一个物种,我会连接它的序列,如果没有,我连接间隙(' - '),与其余序列的长度相同。 (参见文件已对齐)
species_list = []
files = [file for file in glob.glob('~/*.fa')]
for aln in files:
with open (aln, 'rU') as multispecies:
sequences = SeqIO.parse(multispecies, 'fasta')
for species in sequences:
species_list.append(species.id)
species_list=list(set(species_list))
#print(species_list)
concat = {}
for aln in files:
#print(aln)
dict = {}
with open (aln, 'rU') as multispecies:
sequences = SeqIO.parse(multispecies, 'fasta')
names = []
for fasta in sequences:
names.append(fasta.id)
dict[fasta.id] = fasta.seq
count_species = 0
for i in species_list:
if i in names:
count_species = count_species + 1
print('>' + i + '\n' + dict[i])
gap = int(len(dict[i]))
concat[i] += dict[i] #I cannot find a way to concatenate here
else:
print('>' + i + '\n' + '-'*gap)
concat[i] += '-'*gap #I cannot find a way to concatenate here
答案 0 :(得分:1)
你的concat应该是一个defaultdict或者通过创建一些可迭代的函数来处理缺失的键,在这种情况下可能是str或者最好是列表。然后,您可以使用新值扩展iterable:
# list-based
concat.setdefault(i, []).extend(dict[i]) # should work if you keep the data in a list
# string-based
concat[i] = concat.get(i, '') + dict[i]
基于字符串的方法效率非常低,因为您必须在每个连接上从头开始重建字符串。如果你需要一个字符串,你总是可以把它作为一个列表然后“”。一旦你完成它就加入它。