Цикл над генератором - PullRequest
       38

Цикл над генератором

0 голосов
/ 26 октября 2018

Я хочу зациклить генератор и выдавать выходы генератора до остановки StopItered.

>>> 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 голосов
/ 26 октября 2018

Я использовал 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)
...