首页 > 解决方案 > checking if a list is a key in a dictionary and returning corresponding value

问题描述

This is my code:

with open('file.txt','r') as f:
    table = {}
    for lines in f:
        co1,co2,co3,pro1,pro2,pro3 = (
            item.strip() for item in lines.split(',',5))
        codon=str(co1 + co2 + co3)
        table[codon] = pro2

print(table)

I need to split the dan_seq whatever they say it is into chunks of 3 and then match it to the dictionary I created i.e. if the chunk is a key in my dictionary, return the value of it

dna_seq = list('AAAGTTAAATAATAAATAGGTGAA')

the picture is the text file:

1

标签: python

解决方案


您可以使用切片来分块dna_seq,然后table.get获取匹配值:

>>> dna_seq = 'AAAGTTAAATAATAAATAGGTGAA'
>>> [dna_seq[i:i+3] for i in range(0, len(dna_seq), 3)]
['AAA', 'GTT', 'AAA', 'TAA', 'TAA', 'ATA', 'GGT', 'GAA']
>>> for chunk in [dna_seq[i:i+3] for i in range(0, len(dna_seq), 3)]:
...     print(table.get(chunk))

推荐阅读