文章目录
1.高阶函数之概念
什么是高阶函数?
高阶函数的实参是一个函数名
高阶函数的返回值也是一个函数
函数本身也可以赋值给变量,变量也可以指向函数
print(abs(-10))
f=abs
print(f(-10)
高阶函数传递的参数包括函数名
def fun(x,y,f):
return f(x),f(y)
print(fun(-4,-1,abs))
结果是:
(4, 1)
2 高阶函数map
map():接收两个参数 一个是函数 一个是序列
map将传入的函数依次作用到序列的每个元素 并且把结果作为新的序列返回.
2.1 对一个序列[-1,3,-4,-5]的每一个元素求绝对值
print(list(map(abs,[-1,3,-4,-5])))
结果是:
[1, 3, 4, 5]
2.2 对序列的每个元素求阶乘
import random
def f(x):
res = 1
for i in range(1,x+1):
res = res*i
return res
li = [random.randint(2,7) for i in range(10)]
print(li)
print(list(map(f,li)))
结果是:
[5, 5, 3, 6, 3, 2, 7, 5, 5, 5]
[120, 120, 6, 720, 6, 2, 5040, 120, 120, 120]
3 高阶函数reduce
reduce():把一个函数作用在一个序列上,这个函数必须接收两个参数
reduce把结果继续和序列的下一个元素做累积计算。
reduce(f,[1,2,3,4]) = f(f(f(1,2),3),4)
在python2和python3中高阶函数reduce区别:
python2:reduce是内置函数
python3:from functools import reduce.
3.1 计算序列中x y累乘的结果
from functools import reduce
def multi(x,y):
return x*y
print(reduce(multi,range(1,10)))
结果是:
362880
3.2 计算序列中x y累加的结果
from functools import reduce
def add(x,y):
return x+y
print(reduce(add,range(1,10)))
结果是:
45
4 高阶函数filter
filter()过滤函数:接收两个参数,一个是函数,一个是序列
filter函数把传入的函数依次作用于序列中的每个元素,然后根据返回值是True或False来决定保留或丢弃该元素
4.1 将100以内的偶数以列表形式输出
def isodd(num):
if num%2==0:
return True
else:
return False
print(list(filter(isodd,range(1,10))))
结果是:
[2, 4, 6, 8]
5 高阶函数sorted
格式如下:
sorted(序列,key=函数名)
默认sort方法和sorted函数均由小到大排序,reverse=True由大到小排序。
li=[2,3,1,5,32,5]
li.sort()
print(li)
li.sort(reverse = True)
print(li)
结果是:
[1, 2, 3, 5, 5, 32]
[32, 5, 5, 3, 2, 1]
5.1 对列表进行排序
li = [2,3,4,1,6,5,8,3]
li1=li[:]
li1.sort()
print(li1,li)
li2 = sorted(li)
print(li2,li)
li3=[4,-5,-9,-7,8]
li4=sorted(li3,key=abs)
print(li4)
结果是:
[1, 2, 3, 3, 4, 5, 6, 8] [2, 3, 4, 1, 6, 5, 8, 3]
[1, 2, 3, 3, 4, 5, 6, 8] [2, 3, 4, 1, 6, 5, 8, 3]
[4, -5, -7, 8, -9]
5.2 字母排序
s = ['daa','dae','Feew','rde','daw','gu']
print(s)
print(sorted(s))
print(sorted(s,key=str.lower))
print(sorted(s,key=str.upper))
结果是:
['daa', 'dae', 'Feew', 'rde', 'daw', 'gu']
['Feew', 'daa', 'dae', 'daw', 'gu', 'rde']
['daa', 'dae', 'daw', 'Feew', 'gu', 'rde']
['daa', 'dae', 'daw', 'Feew', 'gu', 'rde']
5.3 不同参数排序
info = [
('apple1',20,100),
('apple2',40,32),
('apple3',30,105),
('apple4',20,15)
]
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', 20, 100), ('apple4', 20, 15), ('apple3', 30, 105), ('apple2', 40, 32)]
[('apple4', 20, 15), ('apple2', 40, 32), ('apple1', 20, 100), ('apple3', 30, 105)]
[('apple4', 20, 15), ('apple1', 20, 100), ('apple3', 30, 105), ('apple2', 40, 32)