map函数
num_l=[1,5,12,56,23]
#lambda x:x+1
def add_one(x):
return x+1
def reduce_one(x):
return x-1
def pf(x):
return x**2
def map_test(func,array):
ret=[]
for i in array:
res=func(i) #add_one(i)
ret.append(res)
return ret
print(map_test(add_one,num_l))
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='frommsgtest'
print(list(map(lambda x:x.upper(),msg)))
filter函数
movie_people=['test_df','test_dgdfgdf','sdfsd','test_trbrrt']
def filter_test(array):
ret=[]
for p in array:
if not p.startswith('test'):
ret.append(p)
return ret
print(filter_test(movie_people))
movie_people=['df_test','dgdfgdf_test','sdfsd','trbrrt_test']
def test_show(n):
return n.endswith('test')
def filter_test(func,array):
ret=[]
for p in array:
if not func(p):
ret.append(p)
return ret
res=filter_test(test_show,movie_people)
print(res)
#lambda x:x+1
movie_people=['df_test','dgdfgdf_test','sdfsd','trbrrt_test']
# def test_show(n):
# return n.endswith('test')
#--->lambda n:n.endswith(test')
def filter_test(func,array):
ret=[]
for p in array:
if not func(p):
ret.append(p)
return ret
res=filter_test(lambda n:n.endswith('test'),movie_people)
print(res)
movie_people=['df_test','dgdfgdf_test','sdfsd','trbrrt_test']
print(filter(lambda n:n.endswith('test'),movie_people))
print(list(filter(lambda n:n.endswith('test'),movie_people))) #布尔值
print(list(filter(lambda n:not n.endswith('test'),movie_people))) #布尔值
reduce函数
# from functools import reduce
# res=0
# for num in num_l:
# res+=num
#
# print(res)
# def reduce_test(array):
# res=1
# for num in array:
# res+=num
# return res
#
# print(reduce_test(num_l))
num_l=[1,3,4,7,23,89]
# def multi(x,y):
# return x*y
# lambda x,y: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))
num_l=[2,3,4,7,23,89]
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,2))
#reduce函数
from functools import reduce
num_l=[1,2,3,100]
print(reduce(lambda x,y:x+y,num_l,1))