python map函数,filter函数,reduce函数

 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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值