高阶函数:两种类型
- 函数的参数类型是一个函数类型那么我们称为这样的函数为高阶函数
- 函数的返回值是一个函数类型那么这样的函数也可以称为是高阶函数
Python内部的高阶函数
1. map(function(x),container)
函数 function 对容器container type(字符串、列表、字典、元组、集合)中的每一个元素进行操作,返回一个包含所有function 函数返回值的 map 对象,可以使用 list() 将其转换成一个新列表。
例a:计算每一个元素的平方值
my_list = [1, 2, 3, 4, 5]
def f(x):
return x ** 2
result = map(f, my_list)
print(type(result), result, list(result))
===输出结果:======================================================================
<class 'map'> <map object at 0x000000C9729591D0> [1, 4, 9, 16, 25]
高阶函数map结合匿名函数使用:
result = map(lambda x: x ** 2, my_list)
print(result)
===输出结果:======================================================================
[1, 4, 9, 16, 25]
例b:首字母大写
my_list = ['smith', 'edward', 'john', 'obama', 'tom']
def f(x):
return x[0].upper() + x[1:]
result = map(f(x), my_list)
print(list(result))
===输出结果:======================================================================
['Smith', 'Edward', 'John', 'Obama', 'Tom']
高阶函数map结合匿名函数使用:
result = map(lambda x: x[0].upper() + x[1:], my_list)
print(result)
===输出结果:======================================================================
['Smith', 'Edward', 'John', 'Obama', 'Tom']
2. reduce(function(x1,x2),container)
函数 function(有两个参数)先对容器中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算, 最后得到一个结果。
例c:计算列表中的累加和
import functools # 或者from functools import reduce
my_list = [1, 2, 3, 4, 5]
def f(x1, x2):
return x1 + x2
result = functools.reduce(f(x1, x2), my_list)
print(result)
===输出结果:======================================================================
15
高阶函数reduce结合匿名函数使用:
result = functools.reduce(lambda x1, x2: x1 + x2, my_list)
print(result)
===输出结果:======================================================================
15
3. filter(function(x),container)
函数 function 对容器container type(字符串、列表、字典、元组、集合)中的每一个元素进行判断(过滤)操作,然后返回 True 或 False, 最后将返回值为 True 的所有元素放到一个 filter 对象中,可以使用 list() 将其转换成一个新列表。
例d:过滤列表中的偶数
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def f(x):
return x % 2 == 0
result = filter(f, my_list)
print(list(result))
===输出结果:======================================================================
[2, 4, 6, 8, 10]
高阶函数filter结合匿名函数使用:
result = filter(lambda x: x % 2 == 0, my_list)
print(list(result))
===输出结果:======================================================================
[2, 4, 6, 8, 10]
例e:过滤列表中首字母为大写的单词
my_list = ['edward', 'Smith', 'Obama', 'john', 'tom']
def f(x):
return x[0].isupper()
result = filter(f, my_list)
print(list(result))
===输出结果:======================================================================
['Smith', 'Obama']
高阶函数filter结合匿名函数使用:
result = filter(lambda x: x[0].isupper(), my_list)
print(list(result))
===输出结果:======================================================================
['Smith', 'Obama']