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

posted @ 2015-07-23 16:51  XiaoweiLiu  阅读(510)  评论(0编辑  收藏  举报