(六)高阶函数

高阶函数

函数接收的参数是一个函数名,或返回值中包含函数,这样的函数称为高阶函数

def test(n):
    print(n)
def aaa(name):
    print('my name is %s'%name)
test(aaa)
test(aaa('xulan'))
结果:<function aaa at 0x0000000000A77048>
    my name is xulan
    None       --因为aaa函数没有返回值,所以这里为None
def test1():
    print('from test1')
def test2():
    print('from test2')
    return test1()
res = test2()
print(res)
结果:from test2
    from test1
    None       --因为test1函数没有返回值,所以这里为None

map函数(把列表中的元素都处理一遍,最后返回列表的元素个数与位置都与原来的一样)

需求:把一个列表每个元素自加一

num_li = [1,3,12,6,8,11]
def map_test(func,array):
    li = []
    for i in array:
        res = func(i)
        li.append(res)
    return li
print(map_test(lambda x:x+1,num_li))
结果:[2, 4, 13, 7, 9, 12]

以上代码用map函数实现,map函数第一个参数为一个函数(实现需要处理的逻辑,如果逻辑简单可以用lambda,返回一个非布尔值),第二个参数为可迭代对象(列表,元组,字符串)

map函数返回值也是一个可迭代对象,最后可以用list()转为列表

num_li = [1,3,12,6,8,11]
print(map(lambda x:x+1,num_li))          
print(list(map(lambda x:x+1,num_li)))
结果:<map object at 0x000000000118C780> ----map函数返回值为一个可迭代对象
   [2, 4, 13, 7, 9, 12]
num_li = 'abc'
print(list(map(lambda x:x.upper(),num_li)))
结果:['A', 'B', 'C']

 filter函数(把列表中的元素删选一遍,判断每个元素得到布尔值,如果是True则留下来,最后返回的列表中只剩下删选过后的元素)

需求:把一个列表每个元素判断是否以‘a’开头

move_li = ['a_s','a_dw','c','a_oi']
def test(func,array):
    res = []
    for i in array:
        if func(i):
            res.append(i)
    return res
print(test(lambda x:x.startswith('a'),move_li))
结果:['a_s', 'a_dw', 'a_oi']

以上代码用filter函数实现,filter函数第一个参数为一个函数(实现需要处理的逻辑,如果逻辑简单可以用lambda,返回一个布尔值),第二个参数为可迭代对象(列表,元组,字符串)

filter函数返回值也是一个可迭代对象,最后可以用list()转为列表

move_li = ['a_s','a_dw','c','a_oi']
print(list(filter(lambda x:x.startswith('a'),move_li)))
结果:['a_s', 'a_dw', 'a_oi']
people=[
    {'name':'aaa','age':1000},
    {'name':'bbb','age':10000},
    {'name':'ccc','age':9000},
    {'name':'ddd','age':18},
]
print(list(filter(lambda p:p['age']<=18,people)))
结果:[{'age': 18, 'name': 'd'}]

reduce函数(合并列表中的元素,得到一个最终的结果)

需求:一个初始值 + 一个列表中所有元素的和

num_li = [1,2,3,4,5,10]
def test(func,array,init = None):
    if init is None:
        res = num_li.pop(0)
    else:
        res = init
    for i in num_li:
        res = func(res,i)
    return res
print(test(lambda x,y:x+y,num_li,10))
结果:35

以上代码用reduce函数实现,reduce函数第一个参数为一个函数(实现需要处理的逻辑,如果逻辑简单可以用lambda,返回一个非布尔值),第二个参数为可迭代对象(列表,元组,字符串),第三个参数为初始值

reduce函数返回值是一个最终的结果

from functools import reduce        ----python2直接用,python3需要导入模块
num_li = [1,2,3,4,5,10]
print(reduce(lambda x,y:x+y,num_li,10))
结果:35
from functools import reduce
print(reduce(lambda x,y:x+y,range(100),100))
结果:5050

猜你喜欢

转载自www.cnblogs.com/xulan0922/p/9208687.html