for控制結(jié)構(gòu)允許重復(fù)執(zhí)行代碼厢绝,同時(shí)保留一個(gè)具有可迭代對(duì)象值的變量曲秉。
base=['T','C','G','A']
for x in base:
print(x)
T
C
G
A
要知道你正在迭代的可迭代對(duì)象的位置二蓝,enumerate方法將返回可迭代對(duì)象的索引和值翘盖。
base=['T','C','G','A']
for n,x in enumerate(base):
print(n,x)
0 T
1 C
2 G
3 A
迭代數(shù)字列表的方法是使用內(nèi)置函數(shù)range(n)。
for x in range(4):
print(x)
0
1
2
3
例:計(jì)算蛋白質(zhì)的凈重瓶摆。
prot_seq=input('請(qǐng)輸入氨基酸序列:')
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) #減去結(jié)合后失去的水分子質(zhì)量
print('蛋白質(zhì)凈重為:{0}'.format(total_weight))
請(qǐng)輸入氨基酸序列:AFTGTGATCGTMATGHQ
蛋白質(zhì)凈重為:1610
但是上面無(wú)法判斷是否輸錯(cuò)了氨基酸序列凉逛,下面加上一個(gè)判斷:
prot_seq=input('請(qǐng)輸入氨基酸序列:')
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}
#判斷輸錯(cuò)的情況
err=0
prot_weight_keys=prot_weight.keys() #取出鍵
keys_list=[] #將鍵放入一個(gè)列表里
for pro in prot_weight_keys:
keys_list.append(pro)
print(keys_list)
for inp in prot_seq: #寫循環(huán)判斷是否有輸錯(cuò)
if inp in keys_list:
pass
else:
err=err+1
print('輸錯(cuò)了{(lán)0}個(gè)氨基酸序列。'.format(err))
total_weight=0 #計(jì)算凈重
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) #減去錯(cuò)誤的氨基酸序列個(gè)數(shù)及水分子質(zhì)量
print('蛋白質(zhì)凈重為:{0}'.format(total_weight))
請(qǐng)輸入氨基酸序列:AFTGTGATCGTBBMATGHQ
['A', 'V', 'L', 'I', 'P', 'F', 'W', 'M', 'G', 'S', 'C', 'T', 'Y', 'N', 'Q', 'D', 'E', 'K', 'R', 'H']
輸錯(cuò)了2個(gè)氨基酸序列群井。
蛋白質(zhì)凈重為:1610