如何避免python中的StopIteration错误



我有一行正在从多个列表中引入变量,我希望它避免出现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()的每个方法捕获异常?

compose_line5中,使用item而不是pointer_list.next()——您已经在pointer_list上迭代了。

对于compose_line6,您似乎希望同时对两个列表进行迭代。使用中的顶部答案是否有更好的方法来迭代两个列表,每次迭代从每个列表中获得一个元素?(我假设两个列表的长度相同)

是的,如果手动调用.next(),迭代器协议将引发StopIteration(不是错误,只是一个异常,表示迭代结束)。使用它的Python方法是将它用作普通迭代器(例如,在它上循环),而不是在它上调用.next()

除此之外,您的代码还有一些问题,您可能希望了解这些问题-了解http://www.python.org/dev/peps/pep-0008/

例如,当''足够时,不需要使用''''''。您可能希望创建一个列表,然后最终加入,而不是执行+=。如果你只是从函数中返回东西,就不知道为什么要把它们存储在自己身上。

最新更新