python四大高阶函数_python 高阶函数

一、基本概念

所谓高阶函数,即一个函数的参数可接收另一个函数或者一个函数的返回值为另一个函数,满足两者之一就称为高阶函数。

二、自定义高阶函数

#参数为函数

def hi(a):

print('There is a{}.'.format(a))

return a

def eat(b, c):

b(c)

print('The{}is eating.'.format(c))

#返回值为函数

def eat2(a):

print('The{}is eating.'.format(a))

def hi2(b):

print('There is a{}.'.format(b))

return eat2

调用:eat(hi, ‘cat’)

输出:

There is a cat.

The cat is eating.

调用:

ret = hi2(‘cat’)

ret(‘cat’)

输出:

There is a cat.

The cat is eating.

三、内置高阶函数

1.map函数

功能:map函数接收的是两个参数,一个是函数,一个是序列,其功能是将序列中的值传至函数处理再依次接收函数返回值至列表内,在python3中,map函数为一个迭代器对象

举例:

ls = [1, 2, 3]

ls2 = list(map(lambda x: x * 2, ls))

print(ls2)

输出:[2, 4, 6]

2.reduce函数

功能:reduce函数会用传给它的函数function(有两个参数)先对序列中的第 1、2 个元素进行操作,得到的结果再与第三个数据用function函数运算,最后得到一个结果

举例:

from functools import reduce

ls = [1, 2 ,3]

ls2 = reduce(lambda x, y:x * 10 + y, ls)

print(ls2)

输出:123

3.filter函数

功能:根据传给它的函数对序列中的元素进行判断,为True则添加进列表中,最后返回一个可迭代对象

举例:

ls = [1, 2, 3, 4, 5]

ls2 = list(filter(lambda x: x % 2 == 0), ls)

print(ls2)

输出:[2, 4]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值