Python学习笔记------map和filter函数

# **************************************map函数**************************************
"""
# map函数,用来处理'序列'(可迭代的对象)中的每个元素,得到的结果是可迭代的对象,该对象元素位置与个数与原来一样
num_l=[1,2,10,5,3,7]


#lambda x:x-1
def reduce_one(x):
    return x-1


# 终极版本
def map_test(func, array):  # func=lambda x:x+1    arrary=[1,2,10,5,3,7]
    ret = []
    for i in array:
        res = func(i)  # add_one(i)
        ret.append(res)
    return ret


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 = 'linhaifeng'
print(list(map(lambda x: x.upper(), msg)))

"""
"""
# filter 遍历'序列'(可迭代的对象)中的每个元素,判断每个元素,得到一个bool值,如果是True则保留原来的元素
movie_people = ['alex_sb', 'wupeiqi_sb', 'linhaifeng', 'yuanhao_sb']

def filter_test(func, array):
    ret = []
    for p in array:
        if func(p):
            ret.append(p)
    return ret


res = filter_test(lambda n: n.endswith('sb'), movie_people)
print(res)

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

print(list(filter(lambda n: not n.startswith('sb'), movie_people)))
"""

"""
# reduce:处理一个'序列',把序列进行合并操作,

from functools import reduce
num_l=[1,2,3,100]
print(reduce(lambda x,y:x+y,num_l,1))
print(reduce(lambda x,y:x+y,num_l))
""

猜你喜欢

转载自blog.csdn.net/weixin_39180334/article/details/81072588