Python 产生多个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16856251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:49:17  来源:igfitidea点击:

Yield multiple values

python

提问by Shyam Sunder

Can't we yield more than one value in the python generator functions?

我们不能在 python 生成器函数中产生多个值吗?

Example,

例子,

In [677]: def gen():
   .....:     for i in range(5):
   .....:         yield i, i+1
   .....:         

In [680]: k1, k2 = gen()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-680-b21f6543a7e9> in <module>()
----> 1 k1, k2 = a()

ValueError: too many values to unpack

This works as follows:

其工作原理如下:

In [678]: b = a()

In [679]: list(b)
Out[679]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]

Same results even when I do this:

即使我这样做,结果也一样:

In [692]: def a():
    for i in range(5):
        yield i
        yield i+1

Thanks.

谢谢。

采纳答案by Jon Clements

Because gen()returns a generator (a single item - so it can't be unpacked as two), it needs to be advanced firstto get the values...

因为gen()返回一个生成器(单个项目 - 所以它不能被解包为两个),它需要提前获取值......

g = gen()
a, b = next(g)

It works with listbecause that implicitly consumes the generator.

它可以工作,list因为它隐式消耗了生成器。

Can we further make this a generator? Something like this:

我们可以进一步使它成为生成器吗?像这样的东西:

g = gen();
def yield_g():
    yield g.next();
    k1,k2 = yield_g();

and therefore list(k1)would give [0,1,2,3,4]and list(k2)would give [1,2,3,4,5].

因此list(k1)会给予[0,1,2,3,4]并且list(k2)会给予[1,2,3,4,5]

Keep your existing generator, and use izip(or zip):

保留您现有的生成器,并使用izip(或压缩):

from itertools import izip
k1, k2 = izip(*gen())

回答by David Zwicker

Your function genreturns a generator and not values as you might expect judging from the example you gave. If you iterate over the generator the pairs of values will be yielded:

您的函数gen返回一个生成器而不是值,正如您从您提供的示例中所期望的那样。如果您迭代生成器,将产生成对的值:

In [2]: def gen():
   ...:     for i in range(5):
   ...:         yield i, i+1
   ...:         

In [3]: for k1, k2 in gen():
   ...:     print k1, k2
   ...:     
0 1
1 2
2 3
3 4
4 5

回答by forzagreen

Use yield from

yield from

def gen():
    for i in range(5):
        yield from (i, i+1)

[v for v in gen()]
# [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]

The python docssay:

python文档说:

When yield from <expr>is used, it treats the supplied expression as a subiterator.

yield from <expr>被使用时,它把所提供的表达式作为subiterator。