# lambda map reduce方法的使用

### lambda map reduce方法的使用

#lanbda表达式，格式：lambda 参数列表：函数体

#map函数
list1=[1,2,3,4,5]
r=map(lambda x:x+x,list1)
print(list(r))
m1=map(lambda x,y:x*x+y,[1,2,3,4,5],[1,2,3,4,5])
print(list(m1))

#filter过滤器
def is_not_none(s):
return s and len(s.strip())>0
list2=["我是"," ","","老王"]
result=filter(is_not_none,list2)
print(list(result))

#reduce 函数,实现累加
from functools import reduce
f= lambda x,y:x+y
r=reduce(f,[1,2,3,4,5])
print(r)

#列表推导式
#根据已有列表推导出新的列表,若将[]换为{}，则变为集合推导式
list3=[1,2,3,4,5]
f=map(lambda x:x+x,list1)
print(list(f))
list5=[i*i for i in list3 if i*i>3]
print(list5)

#字典推导式
s={
"张三":12,
"李四":23,
"王五":24,
}
#拿出所有的key变为列表
s_key=[key for key,value in s.items()]
print(s_key)
#key和value颠倒
s1={value:key for key,value in s.items() if key=="张三"}
print(s1)

#闭包,一个返回值是函数的函数
#调用后打印当前的时间
import time
def runtime():
def now_time():
print(time.time())
return now_time
f=runtime()
f()


### 读出一个文件中带有某个关键字的行

#读出一个文件中带有某个关键字的行
def make_filter(keep):
def the_filter(file_name):
file=open(file_name)
file.close()
filter_doc=[i for i in lines if keep in i]
return filter_doc
return the_filter
filter1=make_filter("功能")
filter_result=filter1("测试.txt")
print(filter_result)


### 装饰器、语法糖、注解

#装饰器、语法糖、注解
import time
def runctime(func):
def get_time(*args,**kwargs):
print(time.time())
func(*args,**kwargs)
return get_time

@runctime
def student_run():
print("跑步")

@runctime
def student_run2(i,j):
print("跑步")

student_run()
student_run2(1,1)


05-23 1559

06-19 4万+
08-11 298
08-10 2767
08-19 615
09-28 2187
04-22 46
02-10 7万+
04-30 2358