python基础--内置函数filter,reduce

时间:2022-06-22 19:55:42
movie_people=["sb+_alex","sb_wupeiqi","han"]


# def filter_test(array):
#     ret=[]
#     for p in array:
#         if not p.startswith('sb'):
#             ret.append(p)
#
#     return ret
#
# end=filter_test(movie_people)
# print(end)





# movie_people=["alex","sb_wupeiqi","han_sb"]
# def sb_show(n):
#     return n.endswith('sb')
#
# def filter_test(func,array):
#     ret=[]
#     for p in array:
#         if not func(p):
#             ret.append(p)
#
#     return ret
#
# end=filter_test(sb_show,movie_people)
# print(end)



#终极版本
#lambda n:n.startwith('sb')

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.startswith('sb'),movie_people)
print(res)

#filter函数
print(list(filter(lambda n: not n.startswith('sb'),movie_people)))

 

num_1=[1,2,3,4,5,6,100]
res=0
for num in num_1:
    res+=num
print(res)




# def multi(x,y):
#     return x*y

#lambda:x,y:x*y




#num_l=[1,2,3,100]
# def reduce_test(func,array):
#     res=array[0]
#     for num in array:
#         res=func(res,num)
#     return res
# print(reduce_test(lambda x,y:x*y,num_l))




num_l=[1,2,3,100]
def reduce_test(func,array,init=None):
    # 代码中经常会有变量是否为None的判断,有三种主要的写法:
    # 第一种是
    # ` if x is None
    # `;
    # 第二种是
    # ` if not x:`;
    # 第三种是
    # ` if not x is None
    # `(这句这样理解更清晰
    # ` if not (x is None)
    # `)
    if  not init:#init是否为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,100))


from functools import reduce
#reduce函数:合并序列得出最终结果
print(reduce(lambda x,y:x*y,num_l,100))

 

#处理序列中的每个元素,得到的结果是一个'列表',该'列表'元素个数及位置与原来一样
#map()


#fileter遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来,得到结果是一个列表
people=[{"name":"alex","age":10000},{"name":"han","age":1000},{"name":"ou","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))#参数3初始值