不知道为什么我得到StopIteration错误

时间:2017-06-20 23:29:11

标签: python generator stopiteration

我正在编写一个程序,从文件中接收输入,每行可能包含" ATG"或" GTG"而且我很确定我已经完成了一切,正如我想做的那样。这是我第一次在python中使用生成器,在研究了这个问题后,我仍然不知道为什么我会停止迭代。为此,我的生成器必须产生一个元组,其中包含每个字符串中找到的ATG或GTG的起始位置。

import sys

import p3mod


gen = p3mod.find_start_positions()
gen.send(None)   # prime the generator

with open(sys.argv[1]) as f:
    for line in f:
        (seqid,seq) = line.strip().lower().split()
        slocs = gen.send(seq)
        print(seqid,slocs,"\n")

gen.close()  ## added to be more official

这是发电机

def find_start_positions (DNAstr = ""):

    DNAstr = DNAstr.upper()

    retVal = ()
    x = 0
    loc = -1

    locations = []

    while (x + 3) < len(DNAstr):

        if (DNAst[x:x+3] is "ATG" or DNAstr[x:x+3] is "GTG" ):
            loc = x

        if loc is not -1:
            locations.append(loc)

        loc = -1

    yield (tuple(locations))

这是错误:

Traceback (most recent call last):
  File "p3rmb.py", line 12, in <module>
    slocs = gen.send(seq)
StopIteration

4 个答案:

答案 0 :(得分:2)

您创建了一个一次性返回所有数据的生成器。 您应该在每次迭代中产生数据。此代码可能不完美,但它可能会解决您的部分问题:

def find_start_positions (DNAstr = ""):
    DNAstr = DNAstr.upper()

    x = 0
    loc = -1

    while x + 3 < len(DNAstr):
        if DNAst[x:x+3] == "ATG" or DNAstr[x:x+3] == "GTG" :
            loc = x

        if loc is not -1:
            yield loc

        loc = -1

StopIteration不是错误。它是发电机发出信号表明它耗尽了所有数据的方式。你只需要尝试除了&#34;它或者在已经为你做过的forloop中使用你的发电机。 尽管它们并不复杂,但可能需要一些时间才能适应这些“怪异”的问题。错误。 ;)

答案 1 :(得分:2)

您的生成器构建为在其整个生命周期中仅返回一个值。它遍历while循环,找到所有locations,并一举返回整个列表。因此,当您第二次致电send时,您已经耗尽了生成器的操作。

您需要弄清楚您对send的每次调用的期望;配置你的循环以产生那么多,然后yield结果......并继续为将来的send调用做这件事。您的yield语句必须位于循环内才能使其生效。

Jayme 在答案中给了你一个很好的例子。

答案 2 :(得分:0)

有一个内置的find()函数来查找给定字符串中的子字符串。这里真的有发电机吗?

相反,您可以尝试:

import sys

with open(sys.argv[1]) as f:
    text = f.read()

for i, my_string in enumerate(text.strip().lower().split()):
    atg_index = my_string.find('atg')
    gtg_index = my_string.find('gtg')
    print(i, atg_index, gtg_index, my_string)

答案 3 :(得分:0)

def find_start_positions (DNAstr = ""):
    DNAstr = DNAstr.upper()

    x = 0
    loc = -1

    while x + 3 < len(DNAstr):
        if DNAst[x:x+3] == "ATG" or DNAstr[x:x+3] == "GTG" :
            loc = x

        if loc is not -1:
            yield loc

        loc = -1
相关问题