list comprehension & generator expression

List comprehensions(列表推导式) are better when you want to iterate over something multiple times. However,

it's also worth noting that you should use a list if you want to use any of the list methods. Basically, use a

generator expression(生成器推导式/生成器表达式) if all you're doing is iterating once. If you want to store and

use the generated results, then you're probably better off with a list comprehension.

Python 2.7.6 (default, Jun 22 2015, 18:00:18) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> g = (x * 2 for x in xrange(2, 27))
>>> g
<generator object <genexpr> at 0xb71aff04>
>>> g.next()
4
>>> g.next()
6
>>> l = [x * 2 for x in xrange(2, 27)]
>>> l
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52]
>>> type(l)
<type 'list'>
>>> type(g)
<type 'generator'>
>>> l.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'next'
>>> g[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'generator' object has no attribute '__getitem__'
>>> 

生成器推导式( ), 列表推导式[ ]

 

Reference:

Generator Expressions vs. List Comprehension: http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension

转载于:https://www.cnblogs.com/lxw0109/p/list_comprehension_and_generator_expression.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值