简体   繁体   English

打包/拆包发电机

[英]pack/unpack a generator

I have a two generators.我有两个发电机。 First generator sometimes needs to call second generator and yield back values it got from there:第一个生成器有时需要调用第二个生成器并返回它从那里获得的值:

def a():
    for _b in b():
        yield _b

def b():
    yield 1
    yield 2

for _a in a():
    print _a

Is there a more elegant way to do this:有没有更优雅的方法来做到这一点:

for _b in b():
    yield _b

I've tried this:我试过这个:

yield *b()

But surely it doesn't work.但肯定是行不通的。 I have Python 2.6.我有 Python 2.6。

I think you mean PEP380 .我想你的意思是PEP380 It's available from Python 3.3 .可从 Python 3.3 获得 It looks like:看起来像:

 yield from b()

There is no special syntax for that in Python2.在 Python2 中没有特殊的语法。 You just use a for-loop.您只需使用 for 循环。

The a function in your question is actually completely useless.您问题中a function 实际上完全没用。 You can just use b in it's place.你可以在它的地方使用b

You can use a generator expression.您可以使用生成器表达式。 It's about as concise as the loop, plus it indicates that your code is primarily for producing a return value instead of a side effect.它与循环一样简洁,而且它表明您的代码主要用于产生返回值而不是副作用。

def a():
    return (_b for _b in b())

As phihag said, you can probably simply write a = b if your code is really like this example, since a and b return the same sequence.正如 phihag 所说,如果你的代码真的像这个例子,你可能可以简单地写a = b ,因为 a 和 b 返回相同的序列。

Well, in this simple example, you could just write a = b or a = lambda: b .好吧,在这个简单的例子中,你可以只写a = ba = lambda: b But if a adds elements of its own, you can use itertools.chain :但是如果a添加了它自己的元素,你可以使用itertools.chain

import itertools
def a():
  return itertools.chain(['a-value'], b())

Bear in mind that although this variant may be shorter, for: yield is a quite intuitive (and therefore easy to understand) pattern.请记住,尽管此变体可能更短,但for: yield是一种非常直观(因此易于理解)的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM