您好,登录后才能下订单哦!
格式对比:
List Imprehensions 格式:[ 语句 for .. in ..]
Generator 格式:(语句 for .. in ..)
区别:List存储的是具体内容,每个元素都占用空间,当需要存储N条数据时,占用空间大
而Generator存储的是表达式,通过计算而推算出下个元素,因此占空间少。
一、2种输入方式
#!/usr/bin/python
#generator.next()输出:很痛苦的方式
g = (x for x in range(0, 10))
print "g:"
print "1g.next():", g.next();
print "2g.next():", g.next();
print "3g.next():", g.next();
print "4g.next():", g.next();
print "5g.next():", g.next();
print "6g.next():", g.next();
print "7g.next():", g.next();
print "8g.next():", g.next();
print "9g.next():", g.next();
print "10g.next():", g.next();
#print "11g.next():", g.next(); --->超范围后,提示 StopIteration
可见 generator是从中断处继续向下执行。
#for循环输出
k = (x for x in range(0, 10))
for x in k:
print x
二、斐波拉契数列:list 与 generator对比
##Fibonacci : 1 2 3 5 8 13 21 ..
##in list
def fib(n):
i, a, b = 0, 0, 1;
print "in list:"
while i < n:
print b;
a, b = b, a+b
i += 1;
print fib(6);
##in generator -----> yield :generator标志
def fibo(n):
i, a, b = 0, 0, 1;
print "in generator:"
while i < n:
yield b;
a, b = b, a+b
i += 1;
for n in fibo(6):
print n;
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。