您好,登錄后才能下訂單哦!
格式對比:
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。