循环生成器

时间:2018-10-26 02:42:11

标签: python for-loop generator python-3.7

我想遍历一个生成器并产生生成器的输出,直到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

如何仅打印项目,而没有收到错误消息?

1 个答案:

答案 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)