Python:生成器表达式与yield
在Python中,通过生成器表达式创建生成器对象与使用yield语句创建生成器对象有什么区别吗?
使用yield:
def Generator(x, y):
for i in xrange(x):
for j in xrange(y):
yield(i, j)
使用生成器表达式:
def Generator(x, y):
return ((i, j) for i in xrange(x) for j in xrange(y))
两个函数都返回生成器对象,生成元组,例如(0,0)、(0,1)等。
其中之一或的任何优点另一个?想法?
In Python, is there any difference between creating a generator object through a generator expression versus using the yield statement?
Using yield:
def Generator(x, y):
for i in xrange(x):
for j in xrange(y):
yield(i, j)
Using generator expression:
def Generator(x, y):
return ((i, j) for i in xrange(x) for j in xrange(y))
Both functions return generator objects, which produce tuples, e.g. (0,0), (0,1) etc.
Any advantages of one or the other? Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
两者之间只有细微的差别。您可以使用
dis
模块亲自检查此类事情。编辑:我的第一个版本反编译了交互式提示中在模块范围内创建的生成器表达式。这与在函数内部使用的 OP 版本略有不同。我对此进行了修改以匹配问题中的实际情况。
如下所示,“yield”生成器(第一种情况)在设置中具有三个额外的指令,但与第一个
FOR_ITER
相比,它们仅在一个方面有所不同:“yield”方法使用 < code>LOAD_FAST 代替循环内的LOAD_DEREF
。LOAD_DEREF
是“相当慢”< /a> 比LOAD_FAST
快,因此对于足够大的x
值(外循环),它使“yield”版本比生成器表达式稍快,因为 < 的值code>y 每次传递的加载速度稍快一些。对于较小的 x 值,由于设置代码的额外开销,速度会稍微慢一些。还值得指出的是,生成器表达式通常会在代码中内联使用,而不是像那样用函数包装它。这将消除一些设置开销,并使生成器表达式对于较小的循环值稍微更快,即使
LOAD_FAST
为“yield”版本提供了优势。在这两种情况下,性能差异都不足以证明选择其中一种是合理的。可读性更重要,因此请根据当前情况使用最可读的内容。
There are only slight differences in the two. You can use the
dis
module to examine this sort of thing for yourself.Edit: My first version decompiled the generator expression created at module-scope in the interactive prompt. That's slightly different from the OP's version with it used inside a function. I've modified this to match the actual case in the question.
As you can see below, the "yield" generator (first case) has three extra instructions in the setup, but from the first
FOR_ITER
they differ in only one respect: the "yield" approach uses aLOAD_FAST
in place of aLOAD_DEREF
inside the loop. TheLOAD_DEREF
is "rather slower" thanLOAD_FAST
, so it makes the "yield" version slightly faster than the generator expression for large enough values ofx
(the outer loop) because the value ofy
is loaded slightly faster on each pass. For smaller values ofx
it would be slightly slower because of the extra overhead of the setup code.It might also be worth pointing out that the generator expression would usually be used inline in the code, rather than wrapping it with the function like that. That would remove a bit of the setup overhead and keep the generator expression slightly faster for smaller loop values even if
LOAD_FAST
gave the "yield" version an advantage otherwise.In neither case would the performance difference be enough to justify deciding between one or the other. Readability counts far more, so use whichever feels most readable for the situation at hand.
在这个例子中,事实并非如此。但是
yield
可用于更复杂的构造 - 例如它也可以接受来自调用者的值并因此修改流程。阅读 PEP 342 了解更多详细信息(这是一项值得了解的有趣技术)。无论如何,最好的建议是使用更清楚地满足您需求的东西。
PS 这是一个来自 Dave Beazley 的简单协程示例:
In this example, not really. But
yield
can be used for more complex constructs - for example it can accept values from the caller as well and modify the flow as a result. Read PEP 342 for more details (it's an interesting technique worth knowing).Anyway, the best advice is use whatever is clearer for your needs.
P.S. Here's a simple coroutine example from Dave Beazley:
对于可以放入生成器表达式的简单循环类型来说,没有什么区别。然而,yield 可用于创建执行更复杂处理的生成器。这是生成斐波那契数列的简单示例:
There is no difference for the kind of simple loops that you can fit into a generator expression. However yield can be used to create generators that do much more complex processing. Here is a simple example for generating the fibonacci sequence:
在使用中,请注意生成器对象与生成器函数之间的区别。
生成器对象只能使用一次,与生成器函数相反,生成器函数可以在每次再次调用时重复使用,因为它返回一个新的生成器对象。
生成器表达式在实践中通常“原始”使用,而不将它们包装在函数中,并且它们返回一个生成器对象。
例如:
哪个输出:
与稍微不同的用法进行比较:
哪个输出:
并与生成器表达式进行比较:
也输出:
In usage, note a distinction between a generator object vs a generator function.
A generator object is use-once-only, in contrast to a generator function, which can be reused each time you call it again, because it returns a fresh generator object.
Generator expressions are in practice usually used "raw", without wrapping them in a function, and they return a generator object.
E.g.:
which outputs:
Compare with a slightly different usage:
which outputs:
And compare with a generator expression:
which also outputs:
是的,有区别。
对于生成器表达式
(x for var in expr)
,在创建表达式时调用iter(expr)
。当使用
def
和yield
创建生成器时,如:iter(expr)
尚未被调用。仅当迭代g
时才会调用它(并且可能根本不会被调用)。以这个迭代器为例:
这段代码:
while:
由于大多数迭代器不会在 __iter__ 中做很多事情,所以很容易错过这个行为。一个现实世界的例子是 Django 的
QuerySet
,它 在__iter__
中获取数据和data = (f(x) for x in qs)
可能需要很多时间,而def g(): for x in qs: yield f(x)
后跟data=g()
将立即返回。有关更多信息和正式定义,请参阅 PEP 289 -- 生成器表达式。
Yes there is a difference.
For the generator expression
(x for var in expr)
,iter(expr)
is called when the expression is created.When using
def
andyield
to create a generator, as in:iter(expr)
is not yet called. It will be called only when iterating ong
(and might not be called at all).Taking this iterator as an example:
This code:
while:
Since most iterators do not do a lot of stuff in
__iter__
, it is easy to miss this behavior. A real world example would be Django'sQuerySet
, which fetch data in__iter__
anddata = (f(x) for x in qs)
might take a lot of time, whiledef g(): for x in qs: yield f(x)
followed bydata=g()
would return immediately.For more info and the formal definition refer to PEP 289 -- Generator Expressions.
如果表达式比嵌套循环更复杂,那么使用 yield 会很好。除此之外,您还可以返回特殊的第一个值或特殊的最后一个值。考虑:
Using
yield
is nice if the expression is more complicated than just nested loops. Among other things you can return a special first or special last value. Consider:当考虑迭代器时,
itertools
模块:对于性能,请考虑
itertools.product(*iterables[, Repeat])< /代码>
When thinking about iterators, the
itertools
module:For performance, consider
itertools.product(*iterables[, repeat])
在某些情况下,存在一个可能很重要但尚未指出的差异。使用
yield
可以防止您将return
用于 隐式引发 StopIteration(和协程相关的东西)。这意味着这段代码的格式不正确(将其提供给解释器将会给你一个
AttributeError
):另一方面,这段代码的工作原理就像一个魅力:
There is a difference that could be important in some contexts that hasn't been pointed out yet. Using
yield
prevents you from usingreturn
for something else than implicitly raising StopIteration (and coroutines related stuff).This means this code is ill-formed (and feeding it to an interpreter will give you an
AttributeError
):On the other hand, this code works like a charm: