列表包含
a = [9,-2,1,2,3,4,-1]
b = [10*i for i in a if i>0]
print b
print "#"*50
for j in b:
print j
結果:
[90, 10, 20, 30, 40]
##################################################
90
10
20
30
40
生成器表達式
a = [9,-2,1,2,3,4,-1]
b = (10*i for i in a if i>0)
print b
print "#"*50
print b.next()
print b.next()
print "#"*50
for j in b:
print j
結果:
<generator object <genexpr> at 0x0000000001E70CA8>
##################################################
90
10
##################################################
20
30
40
注意與列表包含進行對比
生成器表達式轉成列表包含
a = [9,-2,1,2,3,4,-1]
b = (10*i for i in a if i>0)
print b
#print "#"*50
#print b.next()
#print b.next()
print "#"*50
c = list(b)
print c
print "#"*50
for j in c:
print j
結果:
<generator object <genexpr> at 0x0000000001CC0CA8>
##################################################
[90, 10, 20, 30, 40]
##################################################
90
10
20
30
40
協程,裝飾器,生成器
一個比較集中的例子:
def coroutine(func):
def start(*args,**kwargs):
g = func(*args,**kwargs)
g.next()
return g
return start
@coroutine
def receiver():
print "ready to receive."
try:
while True:
n = (yield)
print "got %s " % n
except GeneratorExit:
print("Receiver done")
r = receiver()
r.send("hello world")
r.close()
r.send("4")
結果:
ready to receive.
got hello world
Receiver done
Traceback (most recent call last):
File "D:/pythonshell/project/test", line 21, in <module>
r.send("4")
StopIteration
因爲調用了r.close()把協程關掉了,所以再次發送r.send(4)的時候會抱異常
遞歸函數
先看一個例子:
import sys
maxdepth = int(sys.getrecursionlimit())
def recursion(n):
if n > maxdepth-2:
print "you exceed the max recursionlimit."
sys.exit(1)
else:
if n < 1:
return 1
else:
return n*recursion(n-1)
print recursion(10)
結果:
3628800
可以算出正確的結果。一般遞歸深度受到sys.getrecursionlimit()函數的影響,默認值是1000,儘管可以增大這個值,但是還是受到系統使用棧的大小的限制。
如果我我們給n複製1000的話,就超過了限制,得到這樣的結果。
you exceed the max recursionlimit.