列表包含
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.