我有一个从多个列表中拉入变量的行,我希望它避免出现StopIteration错误,这样它就可以移到下一行。现在我正在使用break函数,它避免了StopIteration,但只给出了列表中的第一项,如果我要打印它,它会在它后面留下一个空行。
下面是我的两次迭代,它们都有同样的问题。
def compose_line5(self, synset_offset, pointer_list):
self.line5 = ''''''
for item in pointer_list:
self.line5 += '''http://www.example.org/lexicon#'''+synset_offset+''' http://www.monnetproject.eu/lemon#has_ptr '''+pointer_list.next()+'''\n'''
break
return self.line5
def compose_line6(self, pointer_list, synset_list):
self.line6 = ''''''
for item in synset_list:
self.line6 += '''http://www.example.org/lexicon#'''+pointer_list.next()+''' http://www.monnetproject.eu/lemon#pos '''+synset_list.next()+'''\n'''
break
return self.line6这是我在没有断点的情况下得到的错误:
Traceback (most recent call last):
File "wordnet.py", line 225, in <module>
wordnet.line_for_loop(my_file)
File "wordnet.py", line 62, in line_for_loop
self.compose_line5(self.synset_offset, self.pointer_list)
File "wordnet.py", line 186, in compose_line5
self.line5 += '''http://www.example.org/lexicon#'''+self.synset_offset+''' http://www.monnetproject.eu/lemon#has_ptr '''+self.pointer_list.next()+'''\n'''
StopIteration有没有快速修复这个问题的方法,或者我必须为我在其中使用iter()的每个方法捕捉异常?
发布于 2013-06-26 18:48:00
在compose_line5中,不要使用pointer_list.next(),而是使用item -你已经在pointer_list上迭代了。
对于compose_line6,您似乎希望同时迭代两个列表。使用Is there a better way to iterate over two lists, getting one element from each list for each iteration?中最好的答案(我假设两个列表的长度相同)
是的,如果您手动对迭代器协议调用.next(),它将引发StopIteration (不是错误,只是表示迭代结束的异常)。使用它的典型方法是将其用作常规迭代器(例如,在其上循环),而不是在其上调用.next()。
除了这些之外,您的代码还有一些您可能想要查看的问题--看看http://www.python.org/dev/peps/pep-0008/
例如,当''足够时,不需要使用''''''。您可能希望创建一个列表,然后在最后加入,而不是执行+=。如果你只是从函数中返回东西,我不确定为什么要把它们存储在self中。
https://stackoverflow.com/questions/17317900
复制相似问题