1、高阶函数
- 高阶函数
- 实参是一个函数名
- 函数的返回值是一个函数
def fun(a,b):
return a + b
a = fun(1,2)
print(a)
print(abs(-11)) ##abs是求绝对值
运行结果:
3
11
- 函数本身也可以赋值给变量,变量也可以指向函数
f = abs
print(f(-10))
运行结果:
10
- 传递的参数包括函数名
def fun(x,y,f):
return f(x),f(y)
print(fun(-10,23,abs)) ##f为abs函数
运行结果:
(10, 23)
2、内置高阶函数—map
-
map()函数接收两个参数,一个是函数,一个是序列
-
map将传入的函数依次作用到序列的每个元素,并把结果作为新的序列返回
-
例1:对于序列[-1,3,-5,-4]的每个元素求绝对值
print(list(map(abs,[-1,3,-5,-4])))
运行结果:
[1, 3, 5, 4]
- 例2:对于序列的每个元素求阶乘(10个元素,都在2~7之间的随机数)
import random
def jiecheng(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(li)
print(list(map(jiecheng, li)))
运行结果:
[2, 3, 3, 5, 3, 3, 6, 5, 3, 7]
[2, 6, 6, 120, 6, 6, 720, 120, 6, 5040]
- 例3:用户接收一串数字,‘1 3 5 7 8’将字符串中所有的数字转化为整型,并且以列表的格式输出
num = input('输入: ')
print(list(map(int,num.split()))) ##int也是函数
运行结果:
输入: 1 2 3 4
[1, 2, 3, 4]
3、内置高阶函数—reduce
- reduce:把一个函数作用在一个序列上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算。
reduce(f,[x1,x2,x3,x4,x5])= f(f(f(x1,x2),x3),x4)
from functools import reduce
def multi(x,y):
return x * y
print(reduce(multi,range(1,5))) ##1*2*3*4*5
运行结果:
24
from functools import reduce
def add(x,y):
return x + y
print(reduce(add,[1,2,3,4,5]))
运行结果:
15
4、内置高阶函数—filter
- filter:过滤函数和map类似,也接收一个函数和一个序列。但是和map不同是,filter把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
- [ ]列出100内的偶数
def isodd(num):
if num % 2 == 0:
return True
else:
return False
print(list(filter(isodd,range(100))))
运行结果:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
5、内置高阶函数—sorted
- 例1:
li = [2,1,3,4]
li.sort(reverse=True) ##reverse=True是进行降序排序
print(li)
a = sorted(li,reverse=True)
print(a)
运行结果:
[4, 3, 2, 1]
[4, 3, 2, 1]
- 例2
"""
# _*_coding:utf-8 _*_
Name:sorted.py
Date:4/4/19
Author:LiMin-wsp
Connect:314690259@qq.com
Desc:
"""
# li = [2,1,3,4]
# li.sort(reverse=True) ##reverse=True是进行降序排序
# print(li)
# a = sorted(li,reverse=True)
# print(a)
info = {
#商品名称 商品数量 商品价格
('apple1',200,32),
('apple2',40,12),
('apple3',40,2),
('apple4',1000,23),
('apple5',40,5),
}
#按照商品数量进行排序
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))
运行结果:
[('apple3', 40, 2), ('apple5', 40, 5), ('apple2', 40, 12), ('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)]
- 例3:携程春照
"""
# _*_coding:utf-8 _*_
Name:sorted_02.py
Date:4/4/19
Author:LiMin-wsp
Connect:314690259@qq.com
Desc:
"""
"""
# (2018-携程-春招题)题目需求:
给定一个整形数组, 将数组中所有的0移动到末尾, 非0项保持不变;
在原始数组上进行移动操作, 勿创建新的数组;
# 输入:
第一行是数组长度, 后续每一行是数组的一条记录;
4
0
7
0
2
# 输出:
调整后数组的内容;
4
7
2
0
0
"""
n = input('输入: ')
n1 =''.join(n.split())
li = [int(i) for i in n1]
def paixu(item):
if item != 0:
return 1
else:
return 2
print(sorted(li,key=paixu))
运行结果:
输入: 4 0 7 2 0
[4, 7, 2, 0, 0]
6、综合练习
- 利用map和reduce写一个函数,把字符串’123.456’转换成浮点数123.456
"""
# _*_coding:utf-8 _*_
Name:test.py
Date:4/4/19
Author:LiMin-wsp
Connect:314690259@qq.com
Desc:
"""
#利用map和reduce写一个函数,把字符串'123.456'转换成浮点数123.456
from functools import reduce
def str2float(s):
def fun(x,y):
return x * 10 + y
def char2num():
return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[s]
n = s.index('.')
s1 = list(map(int,[x for x in s[:n]]))
s2 = list(map(int,[x for x in s[n+1:]]))
return reduce(fun,s1) + reduce(fun,s2) / 10 ** len(s2)
print('str2float(\'123.456\')=',str2float('123.456'))
运行结果:
str2float('123.456')= 123.456