map
num_l = [1,6,8,9] def map_test(func,array): ret = [] for i in array: res = func(i) ret.append(res) return ret def jia(x): return x+1 #内置函数 print(map_test(lambda x:x+1,num_l)) print(map_test(jia,num_l)) #只能迭代一次 # res = map(lambda x:x+1,num_l) # for i in res: # print(i) # print(list(res))
filter
#filter函数 movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb'] print(filter(lambda n:not n.endswith('sb'),movie_people)) res=filter(lambda n:not n.endswith('sb'),movie_people) print(list(res)) print(list(filter(lambda n:not n.endswith('sb'),movie_people)))
reduce
# def reduce_test(func,array): # res=array.pop(0) # for num in array: # res=func(res,num) # return res # # print(reduce_test(lambda x,y:x*y,num_l)) num_l=[1,2,3,100] def reduce_test(func,array,init=None): if init is None: res=array.pop(0) else: res=init for num in array: res=func(res,num) return res print(reduce_test(lambda x,y:x*y,num_l,100))
#处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来一样 # map() #filter遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来 people=[ {'name':'alex','age':1000}, {'name':'wupei','age':10000}, {'name':'yuanhao','age':9000}, {'name':'linhaifeng','age':18}, ] print(list(filter(lambda p:p['age']<=18,people))) #reduce:处理一个序列,然后把序列进行合并操作 from functools import reduce print(reduce(lambda x,y:x+y,range(100),100)) print(reduce(lambda x,y:x+y,range(1,101)))