# 計(jì)算堿基數(shù)目
list("ATGC")
['A', 'T', 'G', 'C']
for c in 'ATCG':
print(c)
A
T
C
G
第一種 列表迭代
# 定義函數(shù)
def count_v1(dna, base):
dna = list(dna) # 將堿基字母字符串轉(zhuǎn)換成列表
i = 0 # 計(jì)數(shù)
for c in dna:
if c == base:
i += 1
return i
count_v1("ATGCCCATG", "C")
3
第二種 字符串迭代
# 可以將 count_v1 修改
def count_v2(dna, base):
i = 0
for c in dna:
if c == base:
i += 1
return i
dna = 'ATGCGGGAGGACCC'
base = 'C'
n = count_v2(dna, base)
print('%s appears %d time in %s' % (base, n, dna))
C appears 4 time in ATGCGGGAGGACCC
print('{base} appears {n} times in {dna}'.format
(base = base, n = n, dna = dna))
C appears 4 times in ATGCGGGAGGACCC
def count_v2_demo(dna, base):
print('dna: ', dna)
print('base: ', base)
i = 0
for c in dna:
print('c: ', c)
if c == base:
print('True if test')
i += 1
print(i,'\n')
return i
n = count_v2_demo('ATGCGGACCTAT', 'C')
print('\n{base} appears {n} times in {dna}'.format
(base = base, n = n, dna = dna))
dna: ATGCGGACCTAT
base: C
c: A
c: T
c: G
c: C
True if test
1
c: G
c: G
c: A
c: C
True if test
2
c: C
True if test
3
c: T
c: A
c: T
C appears 3 times in ATGCGGGAGGACCC
第三種 索引迭代
def count_v3(dna ,base):
i = 0
for j in range(len(dna)):
if dna[j] == base:
i += 1
return i
count_v3('ATGCGGACCTAT', 'C')
3
第四種 While 循環(huán)
# While 循環(huán)
def count_v4(dna, base):
i = 0
j = 0
while j < len(dna):
if dna[j] == base:
i += 1
j += 1
return i
count_v4('ATGCGGACCTAT', 'C')
3
第五種 創(chuàng)建一個(gè)布爾列表,然后計(jì)數(shù)
# 創(chuàng)建一個(gè)布爾列表宏娄,然后計(jì)數(shù)
def count_v5(dna, base):
m = []
for c in dna:
if c == base:
m.append(True)
else:
m.append(False)
return sum(m)
count_v5('ATGCGGACCTAT', 'C')
3
第六種
# 內(nèi)置 if
def count_v6(dna, base):
m = []
for c in dna:
m.append(True if c == base else False)
return sum(m)
count_v6('ATGCGGACCTAT', 'C')
3
第七種
# 直接統(tǒng)計(jì)布爾值
def count_v7(dna, base):
m = [] # 如果 dna[i] == base, m[i] = True
for c in dna:
m.append(c == base)
return sum(m)
count_v7('ATGCGGACCTAT', 'C')
3
第八種
def count_v8(dna, base):
m = [c == base for c in dna]
return sum(m)
count_v8('ATGCGGACCTAT', 'C')
3
第九種
# 基于第八種進(jìn)一步簡化
def count_v9(dna, base):
return sum([c == base for c in dna])
count_v9('ATGCGGACCTAT', 'C')
3
第十種
def count_v10(dna, base):
return sum(c == base for c in dna)
count_v10('ATGCGGACCTAT', 'C')
3
第十一種
def count_v11(dna, base):
return len([i for i in range(len(dna)) if dna[i] == base])
count_v11('ATGCGGACCTAT', 'C')
3