给定生成器表达式:
a = (x for x in range(3))
print(next(a)) # 0
print(next(a)) # 1
print(next(a)) # 2
print(next(a)) # StopIteration
exception 0 1 2
--------------------------------------------------------------------------- StopIteration
Traceback (most recent call last)
<ipython-input-40-863a9b3464a7> in <module>()
3 print(next(a))
4 print(next(a))
----> 5 print(next(a))
StopIteration:
当&#34; StopIteration异常&#34;如何实现生成器?会发生,然后它倒退&#34;到开头,再次返回0?
答案 0 :(得分:3)
您可以使用itertools.cycle(iterable)方法。
它需要一个iterable作为参数并循环遍历其项目。
>>>cycle('ABCD') --> A B C D A B C D A B C D