函数4(map,filter,reduce)

时间:2020-12-23 18:28:59
 1 a = [1,2,3,4,5,6,4,7]
 2 x = 0
 3 for i in a:
 4     a[x] = i**2
 5     x += 1
 6 print(a)
 7 
 8 l = [1,5,7,9,16]
 9 def add_l(x):
10     return x+1
11 new_l = []
12 def hs(x):
13     for i in l:
14         new_l.append(i**2)
15     return new_l
16 print(hs(l))
17 
18 l = [1,5,7,9,16]
19 def cf_l(x):
20     return x**2
21 def newlb(func,x):
22     nl = []
23     for i in x:
24         nl1 = func(i)
25         nl.append(nl1)
26     return nl
27 print(newlb(cf_l,l))
28 
29 l = [1,5,7,9,16]
30 
31 def newlb(func,x):
32     nl = []
33     for i in x:
34         nl1 = func(i)
35         nl.append(nl1)
36     return nl
37 print(newlb(lambda x:x**2,l))
38 
39 print(list(map(lambda x:x**2,l)))   #map函数了解一下:处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数与位置与原来一样
40 
41 movie = ['stt','abcd','aave','awp']
42 
43 def filter_a(x):                          #找出不以a开头的元素
44     aaa = []
45     for i in x:
46         if not i.startswith('a'):
47             aaa.append(i)
48     return aaa
49 print(list(filter_a(movie)))
50 
51 movie = ['stt','abcd','aave','awp']
52 
53 def face_a(x):
54     return x.startswith('a')
55 
56 def filter_a(func,array):               #找出不以a开头的元素
57     aaa = []
58     for i in array:
59         if not func(i):
60             aaa.append(i)
61     return aaa
62 # print(list(filter_a(face_a,movie)))
63 print(filter_a(lambda x:x.startswith('a'),movie))
64 
65 print(list(filter(lambda x:not x.startswith('a'),movie)))   #filter函数了解一下:遍历序列中的每个元素,判断每个元素的布尔值,True则留下
66 
67 cc = [1,5,9,7]
68 
69 # lambda x,y:x*y
70 def cf(func,x,init=None):
71     if init is None:            #  ‘==’也行
72         res = x.pop(0)
73     else:
74         res = init
75     for i in x:
76         res = func(i,res)
77     return res
78 
79 print(cf(lambda x,y:x*y,cc))
80 
81 from functools import reduce
82 cc = [1,5,9,7]
83 
84 print(reduce(lambda x,y:x*y,cc))      #reduce函数了解一下,处理一个序列,然后把序列进行合并操作