#lanbda表达式,格式:lambda 参数列表:函数体
add_lambda=lambda x,y:x+y
add_lambda(1,2)#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过滤器defis_not_none(s):return s andlen(s.strip())>0
list2=["我是"," ","","老王"]
result=filter(is_not_none,list2)print(list(result))#reduce 函数,实现累加from functools importreduce
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
defruntime():defnow_time():print(time.time())return now_time
f=runtime()
f()
读出一个文件中带有某个关键字的行
#读出一个文件中带有某个关键字的行defmake_filter(keep):defthe_filter(file_name):file=open(file_name)
lines=file.readlines()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)