高阶函数
实参是一个函数名
-
函数的返回值也是一个函数
#abs 是取绝对值的函数 print(abs(-11)) 结果: 11
-
函数本身也可以赋值给变量,变量也可以指向函数
f = abs
print(f(-10))
结果:
10
- 传递的参数包括函数名
def fun(x,y,f):
return f(x),f(y)
print(fun(-10,34,abs))
结果:
10 34
注意:
f = abs ##把整个函数附值给f
f = abs() ##把函数的返回值附给f
一.内置高阶函数map
map()函数接收两个参数,一个是函数,一个是序列
map将传入的函数依次作用到序列的每个元素,并且把结果作为新的序列返回
- 练习1:对于序列[-1,3,-5,-4]的每个元素求绝对值
print(map(abs,[-1,3,-5,-4]))
会报错:
<map object at 0x7f383af6c0b8>
原因:map()打印的并不是一个列表,而是一个对象,可以将其转换成列表再打印
print(list(map(abs,[-1,3,-5,-4])))
结果:
[1, 3, 5, 4]
- 练习2:对于序列的每个元素求阶乘(10个,2~7之间的随机)
import random
def factoria(x): ##定义个求阶乘的函数
res = 1
for i in range(1,x+1):
res *= i
return res
li = [random.randint(2,7) for i in range(10)] ##定义随机列表
print(list(map(factoria,li)))
结果:
[24, 24, 720, 6, 2, 720, 120, 5040, 720, 720] ##结果随机
二、置高阶函数reduce
reduce:把一个函数作用在一个序列上,这个函数必须接收两个
参数,reduce把结果继续和序列的下一个元素累计计算
例如:
reduce(f,[x1,x2,x3,x4,x5]) = f(f(f(f(x1,x2),x3
注意:reduce函数必须要手动导入
- 例1:求3的阶乘
##使用reduce要先导入
from functools import reduce
def multi(x,y):
return x * y
print(reduce(multi,range(1,4)))
结果:
6
- 例2:求1-5的和
from functools import reduce
def add(x,y):
return x + y
print(reduce(add,[1,2,3,4,5]))
结果:
1+2+3+4+5=15
三、内置高阶函数filter
filter过滤函数和map类似,也接收一个函数和一个序列
但是和map不同的是,filter把传入的函数依次作用于每个元素x4)
然后根据返回值是True还是False决定保留还是丢弃该元素
- 练习:求1~25之间的偶数
def isodd(num):
if num % 2 == 0:
return True
else:
return False
print(list(filter(isodd,range(20))))
结果:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
四.sorted函数
- 练习1:倒序
li = [5,3,2,4]
li.sort()
print(li)
等效为:
a = sorted(li)
print(a)
结果:
[2, 3, 4, 5]
- 练习2:对商品进行排序
1.程序内容
info = {
#商品名称 商品数量 商品价格
('apple1',200,32),
('apple2',40,12),
('apple3',40,2),
('apple4',1000,23),
('apple5',40,5),
}
print(sorted(info))
#按照商品数量进行排序:
def sorted_by_count(x):
return x[1]
#按商品价格进行排序
def sorted_by_price(x):
return x[2]
#先按商品数量进行排序,数量相同则按价格进行排序
def sorted_by_count_price(x):
return x[1],x[2]
print(sorted(info,key=sorted_by_count))
print(sorted(info,key=sorted_by_price))
print(sorted(info,key=sorted_by_count_price))
结果:
[('apple1', 200, 32), ('apple2', 40, 12), ('apple3', 40, 2), ('apple4', 1000, 23), ('apple5', 40, 5)]
[('apple3', 40, 2), ('apple2', 40, 12), ('apple5', 40, 5), ('apple1', 200, 32), ('apple4', 1000, 23)]
[('apple3', 40, 2), ('apple5', 40, 5), ('apple2', 40, 12), ('apple4', 1000, 23), ('apple1', 200, 32)]
[('apple3', 40, 2), ('apple5', 40, 5), ('apple2', 40, 12), ('apple1', 200, 32), ('apple4', 1000, 23)]