簡體   English   中英

不知道為什么我收到 StopIteration 錯誤

[英]Don't know why I am getting StopIteration error

我正在編寫一個從文件接收輸入的程序,每一行可能包含“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

您制作了一個一次性返回所有數據的生成器。 您應該在每次迭代中產生數據。 這段代碼可能並不完美,但它可能會解決您的部分問題:

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 不是錯誤。 這是生成器發出信號表示它已耗盡所有數據的方式。 您只需要“嘗試除外”它或在已經為您執行此操作的 forloop 中使用您的生成器。 盡管它們並沒有那么復雜,但習慣這些“奇怪”的錯誤可能需要一些時間。 ;)

您的生成器旨在在其整個生命周期中僅返回一個值。 它遍歷while循環,找到所有locations ,並一舉返回整個列表。 因此,當您第二次調用send時,您已經耗盡了生成器的操作。

您需要弄清楚每次調用send期望值; 配置你的循環以產生那么多,然后yield那個結果......並繼續這樣做以備將來send調用。 您的yield語句必須在循環內才能工作。

Jayme在他的回答中給了你一個很好的例子。

有一個內置的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)
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM