我有一行从多个列表中拉入变量,我希望它避免出现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
,似乎需要同时遍历两个列表。使用Is there a better way to iterate over two lists, getting one element from each list for each iteration?中的最上面的答案 (我假设两个列表的长度相同)是的,如果您手动调用迭代器协议上的
.next()
,迭代器协议将引发StopIteration
(不是错误,只是发出迭代结束信号的异常)。pythonic使用它的方法是将它用作一个普通的迭代器(例如,循环它),而不是对它调用.next()
。您的代码还有一些问题,您可能还想看看-看看http://www.python.org/dev/peps/pep-0008/
例如,当
''
足够时,不需要使用''''''
。与其做+=
,不如创建一个列表,然后在最后加入。如果你只是从函数返回,不知道为什么要在self中存储东西。相关问题 更多 >
编程相关推荐