for控制结构允许重复执行代码,同时保留一个具有可迭代对象值的变量。
base=['T','C','G','A']
for x in base:
print(x)
T
C
G
A
要知道你正在迭代的可迭代对象的位置,enumerate方法将返回可迭代对象的索引和值。
base=['T','C','G','A']
for n,x in enumerate(base):
print(n,x)
0 T
1 C
2 G
3 A
迭代数字列表的方法是使用内置函数range(n)。
for x in range(4):
print(x)
0
1
2
3
例:计算蛋白质的净重。
prot_seq=input('请输入氨基酸序列:')
prot_weight={"A":89, "V":117, "L":131, "I":131, "P":115,
"F":165, "W":204, "M":149, "G":75, "S":105,
"C":121, "T":119, "Y":181, "N":132, "Q":146,
"D":133, "E":147, "K":146, "R":174, "H":155}
total_weight=0
for aa in prot_seq:
total_weight=total_weight+prot_weight.get(aa.upper(),0)
total_weight=total_weight-18*(len(prot_seq)-1) #减去结合后失去的水分子质量
print('蛋白质净重为:{0}'.format(total_weight))
请输入氨基酸序列:AFTGTGATCGTMATGHQ
蛋白质净重为:1610
但是上面无法判断是否输错了氨基酸序列,下面加上一个判断:
prot_seq=input('请输入氨基酸序列:')
prot_weight={"A":89, "V":117, "L":131, "I":131, "P":115,
"F":165, "W":204, "M":149, "G":75, "S":105,
"C":121, "T":119, "Y":181, "N":132, "Q":146,
"D":133, "E":147, "K":146, "R":174, "H":155}
#判断输错的情况
err=0
prot_weight_keys=prot_weight.keys() #取出键
keys_list=[] #将键放入一个列表里
for pro in prot_weight_keys:
keys_list.append(pro)
print(keys_list)
for inp in prot_seq: #写循环判断是否有输错
if inp in keys_list:
pass
else:
err=err+1
print('输错了{0}个氨基酸序列。'.format(err))
total_weight=0 #计算净重
for aa in prot_seq:
total_weight=total_weight+prot_weight.get(aa.upper(),0)
total_weight=total_weight-18*(len(prot_seq)-err-1) #减去错误的氨基酸序列个数及水分子质量
print('蛋白质净重为:{0}'.format(total_weight))
请输入氨基酸序列:AFTGTGATCGTBBMATGHQ
['A', 'V', 'L', 'I', 'P', 'F', 'W', 'M', 'G', 'S', 'C', 'T', 'Y', 'N', 'Q', 'D', 'E', 'K', 'R', 'H']
输错了2个氨基酸序列。
蛋白质净重为:1610