# Python高级用法的详细总结

Lambda表达式也叫匿名函数

lambda参数列表:函数体

list1=[1,2,3,4,5]r=map(lambda x:x+x,list)print(list1(r))

m1=map(lambda x,y:x*x+y,[1,2,3,4,5],[1,2,3,4,5])print(list(ml))

def is_not_none(s): return s and len(s.strip())gt;0list2=['','','hello','xxxx', None,'ai']result=filter(is_not_none, list2)print(list(result))

from functools import reducef=lambda x,y:x+y x=reduce(f,[1,2,3,4,5])print(r)

from functools import reducef=lambda x,y:x+y x=reduce(f,[1,2,3,4,5],10)print(r)

5.1 列表推导式list1=[1,2,3,4,5,6]f=map(lambda x:x+x,list1)print(list(f))list2=[i+i for i in list1]print(list2)list3=[i**3 for i in list1]print(list3)#筛选列表的例子list4=[i*4 for i in list1 if igt;3]print(list4)#结果[2,4,6,8,10,12][2,4,6,8,10,12][1,8,27,64,125,216][16,25,36]

5.2 集合推导式

list1={1,2,3,4,5,6}list2={i+i for i in list1}print(list2)list3={i**3 for i in list1}print(list3)#筛选列表的例子list4={i*4 for i in list1 if igt;3}print(list4)#结果{2, 4, 6, 8, 10, 12}{64, 1, 8, 216, 27, 125}#这里是乱序的{16, 24, 20}

5.3 字典推导式s={"zhangsan":20,"lisi":15,"wangwu":31}#拿出所有的key，并变成列表s_key=[ key for key, value in s.items()]print(s_key)#结果['zhangsan','lisi','wangwu']# 交换key和value位置，注意冒号的位置s1={ value: key for key, value in s.items()}print(s1)#结果{20:'zhangsan',15:'1isi',31:'wangwu'}s2={ key: value for key, value in s.items() if key=="1isi"}print(s2)#结果{"lisi":15}

import time def runtime(): def now_time(): print(time.time())return now_time #返回值是函数名字f=runtime()#f就被赋值为一个函数now_time()了f()#运行f相当于运行now_time()

a，b，c，d，e
1，2，3，4，5
6，7，8，9，10

def make_filter(keep):# keep=8def the_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_filterfilter1=make_filter("8")#这一行调用了make_filter函数，且把8做为参数传给了keep，接受了the_filter函数作为返回值#这里的filter1等于函数the_filterfilter_result=filter1("data.csv")#把文件名data.csv作为参数传给了函数the_filterprint(filter_result)#结果['6,7,8,9,10']

# 这是获取函数结束运行时间的函数import time def runtime(func): def get_time(): func()# run被调用print(time.time())return get_time@runtimedef run()print('student run')#运行run()#结果student run当前时间

#有一个参数import time def runtime(func): def get_time(i): func(i)# run被调用print(time.time())return get_time@runtimedef run(i)print('student run')#运行run(1)#有两个参数import time def runtime(func): def get_time(i,j): func(i,j)# run被调用print(time.time())return get_time@runtimedef run(i,j)print('student run')#运行run(1,2)

#自动适配参数import time def runtime(func): def get_time(*arg): func(*arg)# run被调用print(time.time())return get_time@runtimedef run(i)print('student1 run')@runtimedef run(i,j)print('student2 run')#运行run(1)run(1,2)

#自动适配参数import time def runtime(func): def get_time(*arg,**kwarg): func(*arg,**kwarg)# run被调用print(time.time())return get_time@runtimedef run(i)print('student1 run')@runtimedef run(*arg,**kwarg)print('student2 run')@runtimedef run()print('no param run')#运行run(1)run(1,2,j=4)run()