程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在循环中使用子字符串制作字典 python大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

开发过程中遇到如何在循环中使用子字符串制作字典 python的问题如何解决?下面主要结合日常开发的经验,给出你关于如何在循环中使用子字符串制作字典 python的解决方法建议,希望对你解决如何在循环中使用子字符串制作字典 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(显示在代码和上面)。所以我无法解决的问题是我想以一种字典显示哪些 5mer 来自哪些 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 在 Make a Dictionary with duplicate keys in 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) 

输出:

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

大佬总结

以上是大佬教程为你收集整理的如何在循环中使用子字符串制作字典 python全部内容,希望文章能够帮你解决如何在循环中使用子字符串制作字典 python所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: