【发布时间】:2017-11-23 16:12:37
【问题描述】:
我正在编写一个从文件接收输入的程序,每一行可能包含“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
【问题讨论】:
-
是否打印出显示每一行的回溯?
-
Traceback(最近一次调用最后一次):文件“p3rmb.py”,第 12 行,在
slocs = gen.send(seq) StopIteration -
如果你调用
send,yield需要被赋值。 -
@TylerDunn 我很难理解您在这里使用协程要完成的工作......
-
顺便说一句,不要使用
is来比较字符串。这不是你想要的。
标签: python generator stopiteration