理解下面这段代码:
num_l = [1, 2, 4, 6] def add_one(x): return x + 1 #定义一个自加1的函数 def map_test(func, array): ret = [] for i in array: res = func(i) ret.append(res) return ret print(map_test(add_one, num_l))
print(map_test(lambda x:x + 1, num_l)) #这样更好
用map函数实现
num_l = [1, 2, 4, 6] print(list(map(lambda x:x + 1,num_l))) #map函数得到的是可迭代对象,需要用list方法处理一下
map函数也可以传入自定义函数
num_l = [1, 2, 4, 6] def add_one(x): return x + 1 #定义一个自加1的函数 print(list(map(add_one,num_l)))
用map函数处理字符串
msg = "dabai" print(list(map(lambda x: x.upper(), msg)))
理解下面代码:
movie_people = [‘sb_123‘, ‘sb_456‘, ‘sb_789‘, ‘dabai‘] def filter_test(func, array): ret = [] for i in movie_people: if not func(i): ret.append(i) return ret res = filter_test(lambda x: x.startswith(‘sb‘), movie_people) #想把函数运行的结果保存下来就用变量接收,方便下面使用 print(res)
movie_people = [‘sb_123‘, ‘sb_456‘, ‘sb_789‘, ‘dabai‘] def sb_show(x): return x.startswith(‘sb‘) def filter_test(func, array): ret = [] for i in array: if not func(i): ret.append(i) return ret res = filter_test(sb_show, movie_people) #想把函数运行的结果保存下来就用变量接收,方便下面使用 print(res)
movie_people = [‘sb_123‘, ‘sb_456‘, ‘sb_789‘, ‘dabai‘] print(list(filter(lambda x: not x.startswith(‘sb‘), movie_people)))
people = [ {‘name‘:‘alex‘,‘age‘:10000}, {‘name‘:‘dabai‘,‘age‘:18}, {‘name‘:‘sb‘,‘age‘:90000} ] print(list(filter(lambda x: x[‘age‘] <= 18, people)))
理解下面代码
num_l = [1, 2, 3, 100] 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)) #把列表里的值相乘
num_l = [1, 2, 3, 100] from functools import reduce print(reduce(lambda x,y : x * y, num_l, 100))
from functools import reduce print(reduce(lambda x,y : x + y, range(1,101)))
python课堂整理15---map, filter,reduce函数
原文:https://www.cnblogs.com/dabai123/p/11088575.html