如何一次从Python的生成器函数中获取一个值?

问题:如何一次从Python的生成器函数中获取一个值?

一个非常基本的问题-如何从Python的生成器中获取一个值?

到目前为止,我发现我可以通过写作获得一个gen.next()。我只想确保这是正确的方法?

Very basic question – how to get one value from a generator in Python?

So far I found I can get one by writing gen.next(). I just want to make sure this is the right way?


回答 0

是的,或者next(gen)在2.6+中。

Yes, or next(gen) in 2.6+.


回答 1

在Python <= 2.5中,使用gen.next()。这将适用于所有Python 2.x版本,但不适用于Python 3.x

在Python> = 2.6中,使用next(gen)。这是一个内置函数,更加清晰。它也将在Python 3中工作。

两者最终都调用了一个特殊命名的函数next(),该函数可以通过子类重写。但是,在Python 3中,此功能已重命名为__next__(),以与其他特殊功能保持一致。

In Python <= 2.5, use gen.next(). This will work for all Python 2.x versions, but not Python 3.x

In Python >= 2.6, use next(gen). This is a built in function, and is clearer. It will also work in Python 3.

Both of these end up calling a specially named function, next(), which can be overridden by subclassing. In Python 3, however, this function has been renamed to __next__(), to be consistent with other special functions.


回答 2

使用(适用于python 3)

next(generator)

这是一个例子

def fun(x):
    n = 0
    while n < x:
        yield n
        n += 1
z = fun(10)
next(z)
next(z)

应该打印

0
1

Use (for python 3)

next(generator)

Here is an example

def fun(x):
    n = 0
    while n < x:
        yield n
        n += 1
z = fun(10)
next(z)
next(z)

should print

0
1

回答 3

这是正确的方法。

您也可以使用next(gen)

http://docs.python.org/library/functions.html#next

This is the correct way to do it.

You can also use next(gen).

http://docs.python.org/library/functions.html#next


回答 4

要获取与python 3及更高版本中的生成器对象关联的值,请使用next(<your generator object>)。随后对next()的调用会在队列中产生连续的对象值。

To get the value associated with a generator object in python 3 and above use next(<your generator object>). subsequent calls to next() produces successive object values in the queue.


回答 5

在python 3中您没有gen.next(),但是您仍然可以使用next(gen)。如果您问我,这有点奇怪,但是事实就是这样。

In python 3 you don’t have gen.next(), but you still can use next(gen). A bit bizarre if you ask me but that’s how it is.