生成器:生成器不会把结果保存在一个系列中,而是保存生成器的状态,在每次进行迭代时返回一个值,使用*.next()一个一个显示,不会占用内存
g = (i for i in range(10000000))
g.next() #一般只用来检验生成器
0
g.next()
1
for i in g: #生成器可迭代
print i
关键字:yield
def yield_test():
print ‘first’
yield 1
print ‘second’
yield 2
g = yield_test()
print g.next()
first
1
print g.next()
second
2
生成器应用之:生产者消费者模型
#无缓冲区
import time
def consumer(name):
print ('%s get ready to buy ' %name)
while True:
kind = yield
print ('%s buy kind of %s' %(name,kind))
def producer(name):
c1 = consumer('xinhao')
c2 = consumer('haha')
c1.next()
c2.next()
print ('producer ready to make')
for i in ['la','not la']:
time.sleep(1)
print ('%s made kind of %s '%(name,i))
c1.send(i)
c2.send(i)
producer('kk')
xinhao get ready to buy
haha get ready to buy
producer ready to make
kk made kind of la
xinhao buy kind of la
haha buy kind of la
kk made kind of not la
xinhao buy kind of not la
haha buy kind of not la
#有无缓冲区
import time
huanchong = []
def consumer(name):
print ('%s get ready to buy ' %name)
while True:
kind = yield
huanchong.remove(kind)
print ('%s buy kind of %s' %(name,kind))
def producer(name,*kind):
print ('producer ready to make')
for i in kind:
time.sleep(1)
print ('%s made kind of %s '%(name,i))
huanchong.append(i)
producer('kk','la','not la','te la')
print huanchong
c1 = consumer('haohao')
c1.next()
c1.send('la')
print huanchong
producer ready to make
kk made kind of la
kk made kind of not la
kk made kind of bt la
[‘la’, ‘not la’, ‘bt la’]
haohao get ready to buy
haohao buy kind of la
[‘not la’, ‘bt la’]
生成器应用:迷你聊天机器人
def robot():
res = ''
while True:
received = yield res
if 'hi' in received or 'hello' in received or 'nihao' in received:
res = '你好'
elif 'what' in received or 'wocao' in received:
res = '别惊讶是真的'
elif 'buy' in received:
res = '你要几部'
elif 'price' in received or 'money' in received:
res = '5块钱一部'
elif 'exit' in received:
res = 'bye'
else :
res = 'bye'
chat = robot()
chat.next()
while True:
sr = raw_input('>hao>>>:')
if not sr:
continue
elif sr.lower() == 'q':
print 'exit'
break
else:
response = chat.send(sr)
print response
hao>>>:hi
你好
hao>>>:what
别惊讶是真的
hao>>>:buy
你要几部
hao>>>:money
5块钱一部
hao>>>:exit
bye
hao>>>:q
exit
函数式编程:函数可以认为是变量,因此函数名可以作为变量
内置高阶函数:
map:#将序列中的数值传入前边的函数,返回其值组成的列表
def my(x):
return x**2
map(my,[1,2,3,4])
[1,4,9,16]
reduce: #函数结果传入函数,即迭代调用,((((1+2)+3)+4)+5)
def add(x,y)
return x+y
reduce(add,range(1,5))
10
示例程序:
def jiehcneg(n,m): #阶乘
return n*m
n = input("input:")
print reduce(jiehcneg,range(1,n+1))
input:5
120
filter: #返回值为布尔型
def odd(x):
return x%2==0
filter(odd,[2,3,4,5])[2,4]
示例程序:
def is_prime(n):#判断素数
if n == 1:
return False
else:
for i in range(2,n):
if n%i == 0:
return False
else:
return True
n = input('input:')
prime_list = filter(is_prime,range(1,n))
m = [(i,n-i) for i in prime_list if is_prime(n-i) and i<=n-i]
print m
print 'total:%s' %len(m)
input:20
[(3, 17), (5, 15), (7, 13), (9, 11)]
total:4
匿名函数
定义:lambda 参数名:函数返回值
map(lambda x:x**2,[1,2,3])
[1,4,9]
sorted函数:
sorted返回一个新的对像,而sort则作用于列表本身;且sorted用于所有可迭代对像,而sort仅用于列表
*.sort
l = [20,4,56,34]
l.sort()
print l
print l.sort()
[4, 20, 34, 56]
None
sorted
l = [20,4,56,34]
print sorted(l)
print sorted(l,reverse=True) #逆序排列
print l
[4, 20, 34, 56]
[56, 34, 20, 4]
[20, 4, 56, 34]
按指定索引排序
goods =[['apple',2.00,10],['banana',3.00,30],['computer',400,5]]
sorted(goods ,key=lambda x:x[1]) #按商品的第一个索引排序
[[‘apple’, 2.0, 10], [‘banana’, 3.0, 30], [‘computer’, 400, 5]]
函数作为返回值
闭包:函数嵌套,返回值为函数
def la_sum(*args):
def all_sum():
sum = 0
for i in args:
sum+=i
return sum
return all_sum
print la_sum(1,2,3,4,5)
f = la_sum(1,2,3,4,5)
print f()
当前函数为
15
装饰器:
(1)器:可理解为函数
(2)装饰器实质上是用来装饰函数的
(3)给函数在其原有功能上增加新的功能,可以多加几层包装
装饰器示例
import time
def info(a):
def Timer(fun):
def count_time(*args,**kwargs): #万能装饰器添加参数
start = time.time()
fun(*args,**kwargs)
end = time.time()
use = end - start
print ('当前函数为%s,运行时间为%s' %(fun,use))
return count_time
return Timer
@info('***258***') #语法糖,引用装饰器,传递的是函数名,若有参数需给装饰器加参数
def login():
print('*****login******')
@info('********hahhhhah********')
def index():
print('*****index******')
login()
index()
258
login*
当前函数为,运行时间为1.38282775879e-05
***hahhhhah***
index*
当前函数为,运行时间为2.14576721191e-06