python中列表推导和生成器的区别
1.语法区别
(1)迭代器用[]生成,如:[x*xforxinrange(3)]
(2)生成器用()生成,如:(x*xforxinrange(3))
2.生成结果区别
(1)迭代器生成一个list列表,可以多次被迭代取值
(2)生成器生成一个generator生成器,迭代取值只能用一次,并且结果只能通过迭代的方式取值或者next()方法取值,一次迭代完之后结果就是一个[]空列表,如下:
mygenerator= (x*xforxinrange(3))
#----------
print mygenerator[0],mygenerator[2]#报错TypeError: 'generator' object has no attribute '__getitem__'
#---------------
for a in mygenerator:
print"a=",a
for b in mygenerator:#这次获取空
print"b=",b
#-----------
mygenerator2= [x*x for x in mygenerator]
print "mygenerator2=",mygenerator2
print type(mygenerator2)
mygenerator3 = [x*x for x in mygenerator]
print "mygenerator3=",mygenerator3
print type(mygenerator3)
结果:
mygenerator2= [0, 1, 16]
mygenerator3= []
参考:http://python.jobbole.com/81881/
https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do