我正在研究一些基本的基因编码技术,遇到了一个问题:
我的字典应该是这样的:
codon_dict= {
"A": {
"A": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"T": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"G": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"C": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
}
},
"T": {
"A": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"T": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"G": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"C": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
}
},
"G": {
"A": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"T": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"G": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"C": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
}
},
"C": {
"A": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"T": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"G": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"C": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
}
}
}
不是硬编码,有没有办法从列表构造它?或者迭代一个for循环并构造相同的?
即code_dict["A"]["A"]["A"]应该返回0.0
尝试itertools.product
:
from itertools import product
s = "ATGC"
out = {}
for x, y, z in product(s, repeat=3):
out.setdefault(x, {}).setdefault(y, {})[z] = 0.0
print(out)
打印:
{
"A": {
"A": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"T": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"G": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"C": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
},
"T": {
"A": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"T": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"G": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"C": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
},
"G": {
"A": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"T": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"G": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"C": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
},
"C": {
"A": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"T": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"G": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"C": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
},
}