为什么我的for循环(python)在进行4次迭代后会发生变化?

时间:2018-12-11 12:23:57

标签: python for-loop bioinformatics dna-sequence

我正在尝试编写一个程序,该程序在DNA序列的定义长度的元素之间移动,我无法理解我从循环中获得的输出。在循环的前四个迭代中似乎移帧很好,然后似乎恢复为旧序列。我已经非常努力地理解这种行为,但是我对编程来说还是太陌生了,无法解决这个问题,对此非常感谢。

这是我的代码:

seq = "ACTGCATTTTGCATTTT"

search = "TGCATTTTG"

import regex as re

def 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 1
the count for CTG is 1
the count for TGC is 2
the count for GCA is 2
#I expected 'CAT' next, from here on I don't understand the behaviour

the count for CTG is 1 
the count for ACT is 1
the count for TGC is 2
the count for TGC is 2
the count for TGC is 2
the count for TGC is 2
the count for GCA is 2
the count for CTG is 1
the count for ACT is 1
the count for TGC is 2
the count for TGC is 2
the count for TGC is 2
the count for TGC is 2

很明显,最终我想删除重复的内容,等等,但是由于为什么我的for循环无法正常工作,我希望它使我停滞不前,以使其变得更好。

谢谢

1 个答案:

答案 0 :(得分:4)

text.index始终返回找到的第一个索引。由于您逐个字母地反复访问seq字母,因此,第一次击中先前找到的字母时,您会得到怪异的结果。

第5个字母是第一个重复字母,c,因此text.index('c')返回的第一个c的索引是1,而不是您期望的4-您重复了您上次点击c的时间。

此方法效率低下-您似乎对遍历索引比对字母更感兴趣,因此我将使用:

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))

这不仅效率低下,而且每次都会搜索错误的结果,而不是每次都搜索索引。 findall也是一种低效率的计数方法-字典,尤其是defaultdict可能被构造为更有效地计数。

请注意,您已经可以使用不错的内置程序了:

>>> 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})

最终匹配是字符串结尾的位置,您可以忽略它们。