生成器表达式不具备列表推导能力吗? [英] What's do list comprehensions do that generator expressions don't?

查看:51
本文介绍了生成器表达式不具备列表推导能力吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我们已经在语言中添加了列表推导,并且看到了

它们很好。我们已经为语言添加了生成器表达式,并且看到它们也很好。$ / b

我有点困惑,虽然 - 如果我打算要求2.4,我什么时候才能使用list comp而不是
生成器表达式?


谢谢,

< mike

-

Mike Meyer< mw*@mired.org> http://www.mired.org/home/mwm/

独立的WWW / Perforce / FreeBSD / Unix顾问,电子邮件以获取更多信息。

Ok, we''ve added list comprehensions to the language, and seen that
they were good. We''ve added generator expressions to the language, and
seen that they were good as well.

I''m left a bit confused, though - when would I use a list comp instead
of a generator expression if I''m going to require 2.4 anyway?

Thanks,
<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

推荐答案

Mike Meyer写道:
Mike Meyer wrote:
好的,我们已经在语言中添加了列表推导,并且看到它们很好。我们已经在语言中添加了生成器表达式,并且看到它们也很好。

我有点困惑,但是 - 我什么时候会使用列表comp相反,如果我要要求2.4,那么生成器表达式是什么?
Ok, we''ve added list comprehensions to the language, and seen that
they were good. We''ve added generator expressions to the language, and
seen that they were good as well.

I''m left a bit confused, though - when would I use a list comp instead
of a generator expression if I''m going to require 2.4 anyway?




从不。如果你真的需要一个清单


清单(x * x代表xrange(10))


可悲的是,我们不能删除列表推导到3.0。


-

Robert Kern
rk *** @ ucsd.edu


在草地长高的地狱里

是梦的坟墓允许死亡。

- Richard Harter



Never. If you really need a list

list(x*x for x in xrange(10))

Sadly, we can''t remove list comprehensions until 3.0.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter


Robert Kern写道:
Robert Kern wrote:
Mike Meyer写道:
Mike Meyer wrote:
好的,我们已经在语言中添加了列表推导,并且看到它们很好。我们已经在语言中添加了生成器表达式,并且看到它们也很好。

我有点困惑,但是 - 我什么时候会使用列表comp相反,如果我要要求2.4,那么生成器表达式是什么?
Ok, we''ve added list comprehensions to the language, and seen that
they were good. We''ve added generator expressions to the language, and
seen that they were good as well.

I''m left a bit confused, though - when would I use a list comp instead
of a generator expression if I''m going to require 2.4 anyway?



从不。如果你真的需要一个列表

列表(x * x for x in xrange(10))



Never. If you really need a list

list(x*x for x in xrange(10))




不太正确。如果你发现不太可能的场景,即生成器表达式中列表的构造是一个效率

瓶颈,你可以选择一个列表理解 - 它们是略有的

当你真正想要一个列表时更快:



Not quite true. If you discovered the unlikely scenario that the
construction of a list from the generator expression was an efficiency
bottleneck, you might choose a list comprehension -- they''re slightly
faster when you really do want a list:


python -m timeit" list(x * x代表x in xrange(10))"

100000循环,最佳3:每循环使用6.54

python -m timeit "list(x*x for x in xrange(10))"
100000 loops, best of 3: 6.54 usec per loop


这篇关于生成器表达式不具备列表推导能力吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆