1.map函数:(将列表里的每个元素都进行运算,最后得到原列表)
r = [4, 8, 7, 1] def cat(array): o = [] for i in r: o.append(i**2) return o v = cat(r) print(v)
r = [4, 8, 7, 1] def addone(x): return x+1 def cat(func,array): #(func就是运行方法,array就是值) o = [] for i in r: a = func(i) o.append(a) return o v = cat(addone,cat) print(v)
print(map_test(lambda x:x**2,num_l)) #不定义函数,直接用匿名函数
#终极版本 def map_test(func,array): #func=lambda x:x+1 arrary=[1,2,10,5,3,7] ret=[] for i in array: res=func(i) #add_one(i) ret.append(res) return ret print(map_test(lambda x:x+1,num_l)) res=map(lambda x:x+1,num_l) print(‘内置函数map,处理结果‘,res) # for i in res: # print(i) print(list(res)) print(‘传的是有名函数‘,list(map(reduce_one,num_l))) msg=‘linhaifeng‘ print(list(map(lambda x:x.upper(),msg)))
2.filter函数:一步一步进化成filter函数,类似map函数,第一个参数就是方法(得到一个布尔值,得到ture的值),第二个参数就是一个可迭代对象
(将列表里的每个元素都进行运算,最后得到一个 新列表)
r = ["sbnm","sbo","sbp","longkuiqi"] ret = [] for i in r: if not i.startswith("sb"): ret.append(i) print(ret)
r = ["sbnm","sbo","sbp","longkuiqi"] def cat(array): ret = [] for i in array: if not i.startswith("sb"): ret.append(i) return ret print(cat(r))
r = ["dfssb","fdfsb","esb","longkuiqi"] def dog(n): return n.endswith("sb") def cat(func,array): ret = [] for i in array: if not func(i): ret.append(i) return ret v = cat(dog,r) print(v)
r = ["dfssb","fdfsb","esb","longkuiqi"]
v = list(filter(lambda n:not n.endswith("sb"),r)) #因为默认是返回ture的值,可以用not来得到false的值 print(v)
3.reduce函数:(将列表里的每个元素都进行运算,最后得到一个最终结果)
# from functools import reduce
num = [1,2,3,4,100] res = 0 for i in num: res += i print(res)
def multi(x,y): #注意乘法需要两个参数 return x*y
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))
from functools import reduce num = [45,8,5,4] print(reduce(lambda x,y:x+y,num,2))
4.小结
#处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来一样 # 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)))
原文:https://www.cnblogs.com/newt/p/8998323.html