Python中的高阶函数和内置高阶函数(abs,map,reduce,sorted,filter)

高阶函数

1.实参是一个函数名
2.函数的返回值是一个函数

1.abs:

求绝对值

def fun(a,b):
    return a + b
a = fun(1,2)
print(a)
print(abs(-11))
输出结果:
3
11
1
2
3
4
5
6
7
8

(1)函数本身也可以赋值给变量,变量也可以指向函数

f = abs
print(f(-10))
结果:
10
1
2
3
4

(2)传递的参数包括函数名

def fun(x,y,f):
    return f(x),f(y)
print(fun(-10,23,abs))
结果:
(10, 23)
1
2
3
4
5

注:

f = abs 表示把整个函数本身赋值给f
f = abs() 表示把函数的返回值赋值给f
1
2

2.map:

map()函数接收两个参数,一个是函数,一个是序列
map将传入的函数依次作用到序列的每个元素,并把结果作为新的序列返回

(1)对于序列[-1,3,-5,-4]的每个元素求绝对值

import random
print(map(abs,[-1,3,-5,-4]))
输出回报错:因为map()打印的不是一个列表而是一个对象,可以将其转化成一个列表再打印
print(list(map(abs,[-1,3,-5,-4])))
结果:
[1, 3, 5, 4]
1
2
3
4
5
6

(2)对于序列的每个元素求阶乘(10个元素,都在2~7之间的随机数)

def factoric(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(factoric,li)))
结果:
[5, 4, 4, 7, 3, 6, 2, 5, 6, 6]
[120, 24, 24, 5040, 6, 720, 2, 120, 720, 720]
1
2
3
4
5
6
7
8
9
10
11

练习:
用户接收一串数字,‘1 3 5 7 8’,将字符串中所有的数字转化为整型,并且以列表的格式输出

s = '1 3 5 7 8'
print(list(map(int,s.split())))
结果:
[1, 3, 5, 7, 8]
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    ##只导入funtools包里的reduce工具
#累乘
def multi(x,y):
    return x * y
print(reduce(multi,range(1,5)))
#累加
def add(x,y):
    return x + y
print(reduce(add,[1,2,3,4,5]))
结果:
24
15
1
2
3
4
5
6
7
8
9
10
11
12

4.filter过滤函数

和map()类似,也接收一个函数和一个序列
但fileter()把传入的函数依次作用于每个元素,然后根据返回值
是True还是False来决定保留还是丢弃该元素

例:输出1-100中所有的偶数

def isodd(num):
    if num % 2 == 0:
        return True
    else:
        return False
print(list(filter(isodd,range(100))))
1
2
3
4
5
6

5.sorted:排序函数

reverse=True生成倒序

li = [2,1,3,4]
li.sort(reverse=True)     ##用sort()方法
print(li)
a = sorted(li,reverse=True)   ##用sorted函数
print(a)
结果:
[4, 3, 2, 1]
1
2
3
4
5
6
7

例2:

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)]
  [('apple2', 40, 12), ('apple5', 40, 5), ('apple3', 40, 2), ('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)] 

原文地址:https://www.cnblogs.com/greemmao/p/14245174.html