第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

為什么我的 for 循環(huán)(python)在 4 次迭代后改變行為?

為什么我的 for 循環(huán)(python)在 4 次迭代后改變行為?

浮云間 2021-09-14 15:10:10
我正在嘗試編寫一個(gè)程序,該程序在 DNA 序列的定義長(zhǎng)度的元素中移動(dòng),我無(wú)法理解我從循環(huán)中獲得的輸出。對(duì)于循環(huán)的前四次迭代,它似乎可以很好地進(jìn)行移碼,然后似乎恢復(fù)到舊序列。我已經(jīng)非常努力地理解這種行為,但我對(duì)編程還太陌生,無(wú)法解決這個(gè)問(wèn)題,非常感謝任何幫助。這是我的代碼:seq = "ACTGCATTTTGCATTTT"search = "TGCATTTTG"import regex as redef kmers(text,n):  for a in text:    b = text[text.index(a):text.index(a)+n]    c = len(re.findall(b, text, overlapped=True))    print ("the count for " + b + " is " + str(c))(kmers(seq,3))和我的輸出:the count for ACT is 1the count for CTG is 1the count for TGC is 2the count for GCA is 2#I expected 'CAT' next, from here on I don't understand the behaviourthe count for CTG is 1 the count for ACT is 1the count for TGC is 2the count for TGC is 2the count for TGC is 2the count for TGC is 2the count for GCA is 2the count for CTG is 1the count for ACT is 1the count for TGC is 2the count for TGC is 2the count for TGC is 2the count for TGC is 2顯然,最終我想刪除重復(fù)項(xiàng)等,但是我一直在思考為什么我的 for 循環(huán)沒(méi)有按照我預(yù)期的方式工作,這讓我停下了腳步,使其變得更好。
查看完整描述

1 回答

?
慕勒3428872

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊

text.index始終返回找到的第一個(gè)索引。由于您seq逐個(gè)字母地迭代您 的字母,因此當(dāng)您第一次點(diǎn)擊以前找到的字母時(shí),您會(huì)得到奇怪的結(jié)果。


第 5 個(gè)字母是第一個(gè)重復(fù)的 a c,因此text.index('c')返回第一個(gè)c1的索引,而不是您期望的 4 - 并且您在上一次點(diǎn)擊 時(shí)重復(fù)c。


這種方法效率低下 - 與字母相比,您似乎對(duì)跨索引移動(dòng)更感興趣,所以我會(huì)使用:


for a in range(len(text)-(n-1)):

    b = text[a:a+n]

    c = len(re.findall(b, text, overlapped=True))

    print ("the count for " + b + " is " + str(c))

而不是每次都搜索索引,這既低效又在您的情況下產(chǎn)生錯(cuò)誤的結(jié)果。findall這里也是一種低效的計(jì)數(shù)方式 - 一個(gè)字典,特別是defaultdict可能被構(gòu)造為更有效地計(jì)數(shù)。


請(qǐng)注意,您可以使用已經(jīng)很好的內(nèi)置函數(shù):


>>> from collections import Counter

>>> seq='ACTGCATTTTGCATTTT'

>>> Counter((seq[i:i+3] for i in range(len(seq)-2)))

Counter({'TTT': 4, 'TGC': 2, 'GCA': 2, 'CAT': 2, 'ATT': 2, 'ACT': 1, 'CTG': 1, 'TTG': 1})

最后的點(diǎn)擊是字符串結(jié)束的地方,你可以忽略它們。


查看完整回答
反對(duì) 回復(fù) 2021-09-14
  • 1 回答
  • 0 關(guān)注
  • 263 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)