标签:san 技术 com fibonacci 生成器 pytho import 特性 格式
格式对比: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;
标签:san 技术 com fibonacci 生成器 pytho import 特性 格式
原文地址:http://blog.51cto.com/13502993/2144927