我正在编写一个从文件接收输入的程序,每行可能包含“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 中使用您的生成器。尽管它们并没有那么复杂,但习惯这些“奇怪”的错误可能需要一些时间。;)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句