相关疑难解决方法(0)

在Python 3.0中可以看到generator.next()吗?

我有一个生成系列的生成器,例如:

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 iteration python-3.x

226
推荐指数
3
解决办法
11万
查看次数

在python 3中的yield生成器中没有next()函数

这个问题中,我使用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)

python python-3.x

82
推荐指数
2
解决办法
3万
查看次数

标签 统计

python ×2

python-3.x ×2

iteration ×1