我有一个生成系列的生成器,例如:
def triangleNums():
'''generate series of triangle numbers'''
tn = 0
counter = 1
while(True):
tn = tn + counter
yield tn
counter = counter + 1
Run Code Online (Sandbox Code Playgroud)
在python 2.6中,我可以进行以下调用:
g = triangleNums() # get the generator
g.next() # get next val
Run Code Online (Sandbox Code Playgroud)
但是在3.0中,如果我执行相同的两行代码,我会收到以下错误:
AttributeError: 'generator' object has no attribute 'next'
Run Code Online (Sandbox Code Playgroud)
但是,循环迭代器语法在3.0中有效
for n in triangleNums():
if not exitCond:
doSomething...
Run Code Online (Sandbox Code Playgroud)
我还没有能找到解释3.0行为差异的任何东西.
在这个问题中,我使用Python生成器进行了无休止的序列.但是相同的代码在Python 3中不起作用,因为它似乎没有next()功能.功能的等价物是什么next?
def updown(n):
while True:
for i in range(n):
yield i
for i in range(n - 2, 0, -1):
yield i
uptofive = updown(6)
for i in range(20):
print(uptofive.next())
Run Code Online (Sandbox Code Playgroud)