python课堂整理15---map, filter,reduce函数

一、map函数

处理序列(可迭代对象)中的每一个元素,得到的结果是一个‘列表’(其实是个迭代器),该‘列表’元素个数及位置与原来一样

理解下面这段代码:

num_l = [1, 2, 4, 6]
def add_one(x):
    return x + 1 #定义一个自加1的函数
def map_test(func, array):
    ret = []
    for i in array:
        res = func(i)
        ret.append(res)
    return ret

print(map_test(add_one, num_l))
print(map_test(lambda x:x + 1, num_l))  #这样更好

用map函数实现

num_l = [1, 2, 4, 6]
print(list(map(lambda x:x + 1,num_l)))  #map函数得到的是可迭代对象,需要用list方法处理一下

map函数也可以传入自定义函数

num_l = [1, 2, 4, 6]
def add_one(x):
    return x + 1 #定义一个自加1的函数
print(list(map(add_one,num_l)))

用map函数处理字符串

msg = "dabai"
print(list(map(lambda x: x.upper(), msg)))

二、filter函数

filter遍历序列中的每个元素,判断每个元素得到布尔值,如果是Ture则保留下来

理解下面代码:

movie_people = ['sb_123', 'sb_456', 'sb_789', 'dabai']
def filter_test(func, array):
    ret = []
    for i in movie_people:
        if not func(i):
            ret.append(i)
    return ret
res = filter_test(lambda x: x.startswith('sb'), movie_people) #想把函数运行的结果保存下来就用变量接收,方便下面使用
print(res)

filter内也能自定义函数

movie_people = ['sb_123', 'sb_456', 'sb_789', 'dabai']
def sb_show(x):
    return x.startswith('sb')
def filter_test(func, array):
    ret = []
    for i in array:
        if not func(i):
            ret.append(i)
    return ret
res = filter_test(sb_show, movie_people) #想把函数运行的结果保存下来就用变量接收,方便下面使用
print(res)

用filter函数实现

movie_people = ['sb_123', 'sb_456', 'sb_789', 'dabai']
print(list(filter(lambda x: not x.startswith('sb'), movie_people)))

用filter处理字典

people = [
    {'name':'alex','age':10000},
    {'name':'dabai','age':18},
    {'name':'sb','age':90000}
]
print(list(filter(lambda x: x['age'] <= 18, people)))

三、reduce函数

处理一个序列,然后把序列进行合并操作

理解下面代码

num_l = [1, 2, 3, 100]
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 = [1, 2, 3, 100]
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, 100))   #把列表里的值相乘

使用reduce函数,要先引入functools模块

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

from functools import reduce
print(reduce(lambda x,y : x + y, range(1,101)))

一个奋斗中的产品小白
原文地址:https://www.cnblogs.com/dabai123/p/11088575.html