簡體   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