繁体   English   中英

如何在循环 python 中使用子字符串制作字典

[英]how to make dictionary using substrings in a loop python

我有一个包含数百万个 DNA 序列的 fasta 文件——每个 DNA 序列都有一个 ID。

>seq1
AATCAG #----> 5mers of this line are AATCA and ATCAG
>seq3
AAATTACTACTCTCTA
>seq19
ATTACG #----> 5mers of this line are ATTAC and TTACG

我想要做的是,如果 DNA 序列的长度为 6,那么我制作该行的 5mers(如代码及以上所示)。 因此,我无法解决的问题是,我想以一种字典显示哪些 5mers 来自哪个sequence id的方式制作字典。

这是我的代码,但已经完成了一半:

from Bio import SeqIO
from Bio.Seq import Seq

with open(file, 'r') as f:
    lst = []
    dict = {}
    for record in SeqIO.parse(f, 'fasta'): #reads the fast file 
        if len(record.seq) == 6:  #considers the DNA sequence length
            for i in range(len(record.seq)):
                kmer = str(record.seq[i:i + 5])
                if len(kmer) == 5:
                    lst.append(kmer)
                    dict[record.id] = kmer  #record.id picks the ids of DNA sequences


    #print(lst)
                    print(dict)

所需的字典应如下所示:

dict = {'seq1':'AATCA', 'seq1':'ATCAG', 'seq19':'ATTAC','seq19':'TTACG'}

按照@SulemanElahi 的在 Python 中使用重复键创建字典中的建议使用defaultdict ,因为字典中不能有重复键

from Bio import SeqIO
from collections import defaultdict

file = 'test.faa'

with open(file, 'r') as f:
    dicti = defaultdict(list)
    for record in SeqIO.parse(f, 'fasta'): #reads the fast file 
        if len(record.seq) == 6:  #considers the DNA sequence length
                kmer = str(record.seq[:5])
                kmer2 = str(record.seq[1:])
                dicti[record.id].extend((kmer,kmer2))  #record.id picks the ids of DNA sequences

print(dicti)

for i in dicti:
    for ii in dicti[i]:
        print(i, '   : ', ii) 

output:

defaultdict(<class 'list'>, {'seq1': ['AATCA', 'ATCAG'], 'seq19': ['ATTAC', 'TTACG']})
seq1    :  AATCA
seq1    :  ATCAG
seq19    :  ATTAC
seq19    :  TTACG

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM