lambda匿名函数,map函数,filter函数
1.lambda匿名函数
语法:lambda 形参名:逻辑表达式
例如:
name = 'alex' res = lambda x: x + '_sb' # 语法:lambda 形参名:逻辑表达式 print(res(name))
直接打印print(lambda x:x+_sb')会得到一个内存地址,匿名函数的特点是匿名,用完会被垃圾回收机制回收
2.map函数
语法:map(逻辑表达式,可迭代对象)
例如:
num_l = [1,3,5,7,9] ret = [] def pf(i): return i**2 def map_test(func, array): for i in array: res = func(i) ret.append(res) return ret print(map_test(pf, num_l)) print(list(map(lambda x:x**2, num_l))) # map函数,map(函数规则,可迭代对象)
3.filter函数
语法:filter(函数表达式:可迭代对象)
例如:
# filter_people = ['sb_01','sb_02','sb_03','ok1'] # sert = [] # for p in filter_people: # if not p.startswith('sb'): # sert.append(p) # # print(sert) filter_people = ['sb_01','sb_02','sb_03','ok1'] sert = [] def filter1(func,array): for p in array: if func(p): sert.append(p) return sert print(filter1(lambda n:not n.startswith('sb'), filter_people)) print(filter(lambda n: not n.startswith('sb'), filter_people)) print(list(filter(lambda n: not n.startswith('sb'), filter_people))) print(list(map(lambda n:not n.startswith('sb'), filter_people)))