我想遍历一个生成器并产生生成器的输出,直到StopIteration。
>>> list = [1,2,3,4,5,6]
>>>
>>> def funct_one(list, number):
... for item in list:
... if item > number:
... yield item
...
>>> funct_one(list,0).__next__()
1
>>>
>>>
>>> def another_funct():
... number = 0
... while funct_one(list, number).__next__() != StopIteration:
... yield funct_one(list, number).__next__()
... number += 1
... if funct_one(list, number).__next__() == StopIteration:
... break
...
File "<stdin>", line 7
SyntaxError: 'break' outside loop
>>> for item in another_funct():
... print(item)
...
1
2
3
4
5
6
Traceback (most recent call last):
File "<stdin>", line 3, in another_funct
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration
如何仅打印项目,而没有收到错误消息?
答案 0 :(得分:1)
我使用了except StopIteration
行:
def another_funct():
number = 0
while True:
try:
yield funct_one(list, number).__next__()
number += 1
except StopIteration:
break
for item in another_funct():
print(item)