Very basic question - how to get one value from a generator in Python?
非常基本的问题——如何从Python中的生成器获取一个值?
So far I found I can get one by writing gen.next()
. I just want to make sure this is the right way?
到目前为止,我发现我可以通过写gen.next()得到一个。我只是想确定这是正确的方法?
5 个解决方案
#1
88
Yes, or next(gen)
in 2.6+.
是的,或者是2.6+的下一代(gen)。
#2
45
In Python <= 2.5, use gen.next()
. This will work for all Python 2.x versions, but not Python 3.x
在Python <= 2.5中,使用gen.next()。这将适用于所有Python 2。x版本,但不是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.
在Python >= 2.6中,使用next(gen)。这是一个内置的函数,而且更清晰。它也将在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.
这两个函数最后都调用了一个特殊命名的函数next(),这个函数可以通过子类化来重写。然而,在Python 3中,这个函数被重命名为__next__(),以与其他特殊函数保持一致。
#3
9
This is the correct way to do it.
这是正确的方法。
You can also use next(gen)
.
您还可以使用next(gen)。
http://docs.python.org/library/functions.html#next
http://docs.python.org/library/functions.html下
#4
2
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.
在python 3中没有gen.next(),但是仍然可以使用next(gen)。如果你问我,这有点奇怪,但事实就是如此。
#5
2
Use (for python 3)
使用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
#1
88
Yes, or next(gen)
in 2.6+.
是的,或者是2.6+的下一代(gen)。
#2
45
In Python <= 2.5, use gen.next()
. This will work for all Python 2.x versions, but not Python 3.x
在Python <= 2.5中,使用gen.next()。这将适用于所有Python 2。x版本,但不是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.
在Python >= 2.6中,使用next(gen)。这是一个内置的函数,而且更清晰。它也将在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.
这两个函数最后都调用了一个特殊命名的函数next(),这个函数可以通过子类化来重写。然而,在Python 3中,这个函数被重命名为__next__(),以与其他特殊函数保持一致。
#3
9
This is the correct way to do it.
这是正确的方法。
You can also use next(gen)
.
您还可以使用next(gen)。
http://docs.python.org/library/functions.html#next
http://docs.python.org/library/functions.html下
#4
2
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.
在python 3中没有gen.next(),但是仍然可以使用next(gen)。如果你问我,这有点奇怪,但事实就是如此。
#5
2
Use (for python 3)
使用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