map()、reduce()、filter()总结
map()函数:处理序列中的每一个元素,得到的结果是一个迭代器形式,该迭代器的位置以及元素个数与原来一样。可以处理任何可迭代序列
filter()函数:遍历序列中的每一个元素,判断每个元素得到的布尔值,如果是True则留下来
1 people=[{'name':'alex','age':1000,
2 'name':'alex2','age': 10000,
3 'name':'alex3','age': 9000,
4 'name':'alex4','age': 35,
5 'name':'alex5','age': 18,}]
6 res=(list(filter(lambda x:x['age']<=100,people)))
7 print(res)
[{'name': 'alex5', 'age': 18}]
Process finished with exit code 0
1 movie_perple = ['chenchensb_','linlin','guoguo0','wowowsb_','dascsasb_']
2 # lambda x:x.endswith('sb_')
3 def filte(func,x):
4 array=[]
5 for i in x:
6 if not func(i):
7 array.append(i)
8 return array
9 # res1=filter_test(lambda x:x.endswith('sb_'),movie_perple)
10 # res2=filter_test(lambda x:x.startswith('c'),movie_perple)
11 print(filter(lambda x:x.endswith('sb_'),movie_perple))
12 print(list(filter(lambda x:x.endswith('sb_'),movie_perple)))
13 print(list(filter(lambda x:not x.endswith('sb_'),movie_perple)))
14 # print(res1)
15 # print(res2)
运行结果:
1 <filter object at 0x02D8FCD0>
2 ['chenchensb_', 'wowowsb_', 'dascsasb_']
3 ['linlin', 'guoguo0']
4
5 Process finished with exit code 0
reduce()函数:处理一个序列,然后把序列进行合并
1 from functools import reduce
2 num_l=[1,2,3,4,5]
3 # reduce(函数,可迭代对象,初始值)
4 print(reduce(lambda x,y:x+y,num_l,100))
1 list=[1,2,3,5,6]
2 def reduce_num(func,array,init=None):
3 if init is None:
4 res=list.pop(0)
5 else:
6 res=init
7 for num in array:
8 res=func(res,num)
9 return res
10 result=reduce_num(lambda x,y:x*y,list,100)
11 print(result)
运行结果:
18000
Process finished with exit code 0