[英]How to look up a string in a dictionary?
我有一个文件,该文件在一列中包含3个字母的字符串(对于那些了解生物学的人来说是密码子)的列表。 在我的程序中,我构建了一个字典,其中每个特定的字符串都对应一个指定的字母(对于那些了解生物学的人来说是氨基酸)。 因此,我希望我的程序遍历整个字符串/密码子列表,对于每个密码子,我希望程序在词典中查找并输出给定密码子/字符串对应的字母。 不幸的是,我没有太多使用字典的经验,所以我不确定如何查找它。 我已经尝试过一些东西,但是我总是出错。 变量“ new_codon”包含我正在使用的文件中的字符串/氨基酸列表。 到目前为止,这是我得到的:
codon_lookup = {'GCT': 'A', 'GCC': 'A','GCA': 'A','GCG': 'A', 'TGT':'C','TGC':'C', 'GAT':'D','GAC': 'D', 'GAA':'E','GAG': 'E', 'TTT':'F','TTC': 'F', 'GGT': 'G','GGC': 'G','GGA':'G','GGG': 'G', 'CAT':'H','CAC': 'H', 'ATT':'I','ATC':'I','ATA':'I','AAA':'K','AAG':'K', 'TTA': 'L','TTG': 'L','CTT': 'L','CTC': 'L','CTA': 'L','CTG': 'L', 'ATG': 'M', 'AAT':'N','AAC':'N', 'CCT': 'P','CCC': 'P','CCA': 'P','CCG': 'P', 'CAA': 'Q','CAG': 'Q', 'CGT': 'R','CGC': 'R','CGA': 'R','CGG': 'R','AGA': 'R','AGG': 'R', 'TCT': 'S','TCC': 'S','TCA': 'S','TCG': 'S','AGT': 'S','AGC': 'S', 'ACT': 'T','ACC': 'T','ACA': 'T','ACG': 'T', 'GTT': 'V','GTC': 'V','GTA': 'V','GTG': 'V', 'TGG':'W', 'TAT':'Y', 'TAC':'Y', 'TAA': 'Z', 'TAG': 'Z', 'TGA':'Z'}
for x in new_codon:
codon_lookup[x]
if codon_lookup[x] == ref_aa[x]: # Here I'm comparing it to another list I have from another file to see if they match or don't match
print "1"
else:
print "0"
这将解决您的KeyError
for x in new_codon:
x = x.rstrip() # remove line seperators
...
对于您在评论中的问题。
for x, aa in zip(new_codon, ref_aa):
x = x.rstrip() # remove line seperators
if codon_lookup[x] == aa:
print "1"
else:
print "0"
要检查字典中的值是否使用'is':
for x in new_codon:
if x in codon_lookup:
print "1"
else:
print "0"
如果您要求的元素KeyError
词典中,则会得到一个KeyError
。 并且您要使用"ATC\\r\\n"
而不是"ATC"
。 问题不在代码的这一部分。 您正在阅读带有结尾字符的new_codon
。
您所要做的就是添加一个简单的语句,以从字符串x
的末尾删除末尾字符。
codon_lookup = {'GCT': 'A', 'GCC': 'A',...}
for x in new_codon:
#This statement(`codon_lookup[x]`) was pointless
x = x[:3] # Removes the part after the third character
if codon_lookup[x] == ref_aa[x]: # Here I'm comparing it to another list I have from another file to see if they match or don't match
print "1"
else:
print "0"
如果ref_aa
是一个列表,那么您当然会得到TypeError
。 x
是字符串, ref_aa
是列表; 您不能使用ref_aa[x]
。 要解决此问题,您可以使用enumerate
( enumerate
docs ):
codon_lookup = {'GCT': 'A', 'GCC': 'A',...}
for i,x in enumerate(new_codon):
x = x[:3] # Removes the part after the third character
if codon_lookup[x] == ref_aa[i]: # Changed the 'x' with 'i' for list
print "1"
else:
print "0"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.