【问题标题】:Why does my for loop (python) shift behaviour after 4 iterations?为什么我的 for 循环(python)在 4 次迭代后会改变行为?
【发布时间】:2019-05-12 10:41:51
【问题描述】:

我正在尝试编写一个程序,该程序在定义长度的 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 循环没有按照我的预期工作的问题上,这让我停止了我的工作以使其变得更好。

谢谢

【问题讨论】:

    标签: python for-loop bioinformatics dna-sequence


    【解决方案1】:

    text.index 总是返回找到的第一个索引。由于您逐个字母地迭代 seq,因此当您第一次点击之前找到的字母时,您会得到奇怪的结果。

    第 5 个字母是第一个重复的,c,因此 text.index('c') 返回第一个 c 的索引,1,而不是 4,正如您所期望的那样 - 您重复了上一次点击 @ 987654327@.

    这种方法效率低下 - 您似乎对跨索引而不是字母更感兴趣,所以我会使用:

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

    最后的命中是字符串结束的地方,你可以忽略它们。

    【讨论】:

    • 请不要建议像range(len(text))这样的非pythonic模式,要访问索引,请改用enumerate(text)
    • 可能在结束前停止循环n 步骤,以避免不完全填充的窗口。该示例看起来像 OP 只需要长度为 3 的子字符串,而不是在接近字符串末尾时更短的子字符串。
    • @buran 请不要建议什么是非pythonic,甚至不要使用那个短语。如果您不需要枚举(即索引和字母),我看不出使用它的理由。
    • @tripleee 好点,我只是匆忙输入了一些东西 - 添加。
    • @buran 顺便说一下stackoverflow.com/questions/11901081/…,这是一场有趣的辩论。您可以看到您的意见略微领先,但我想说远未达成明确的共识。
    猜你喜欢
    • 2010-11-23
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 2019-08-29
    • 2011-08-16
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多