一、基础概念
在函数式编程中,我们可以把函数当做变量使用。
1.编程范式
函数式编程是一种编程范式,类似的有命令式编程、声明式编程等。
命令式编程
是面向计算机硬件的抽象,主要思想是关注计算机执行的步骤,即一步一步告诉计算机先做什么再做什么,可以理解为冯诺依曼的指令序列。
声明式编程
以数据结构的形式来表达程序执行的逻辑,主要思想是告诉计算机应该做什么,但不指定具体要怎么做。比如前端的HTML、CSS还有SQL语句。
select * from stu where num > 30
函数式编程
是面向数学的抽象,将计算描述为一种表达式求职,主要思想和声明式编程一致,只关注做什么不关注怎么做。
其中的函数指数学中的函数,即自变量的映射。
2.高阶函数
一个函数接收另一个函数作为参数,这种函数被称为高阶函数。
def high_func(f, arr):
return [f(x) for x in arr]
常用的高阶函数有:
map
根据提供的函数对指定序列做映射,并返回映射后的序列。
map(function, *iterables) --> map object
# function 是序列中每个元素需要执行的操作,可以是匿名函数
# *iterables 是一个或多个序列
大多时候我们要把列表中所有元素一个个传递给一个函数,并收集输出;用匿名函数(lambdas)配合map可以达成更简便的实现方式。
# 通常方式
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
# lambdas与map搭配
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
reduce
需要传入一个含两个参数的函数,然后用这个函数从左至右顺序遍历序列并生成结果。
reduce(function, sequence[, initial]) -> value
# function 是序列中每个元素需要执行的操作,可以是匿名函数
# sequence 是需要执行操作的序列
#initial 是可选的初始参数
from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
print(result)
# print out: 15
# 设定初始参数,序列的数据类型要和初始参数的一致
s = reduce(lambda x, y: x + y, ['1', '2', '3', '4', '5'], "数字 = ")
print(s)
# print out: 数字 = 12345
filter
用来过滤序列中不符合条件的值,返回一个迭代器,生成那些函数为True的iterable项。如果函数为None,则返回为True的项。
filter(function or None, iterable) --> filter object
# function or None 过滤操作执行的函数
# iterable 待过滤的序列
'''排出不能被2整除的数据'''
def boy(n):
if n % 2 == 0:
return True
return False
# 自定义函数
filterlist = filter(boy, list(range(20)))
print(list(filterlist))
# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 或者写,然后再打印
filterlist2 = filter(lambda n: n % 2 == 0, list(range(20)))
sorted
默认将序列升序排序后返回一个新的list,可自定义键函数来排序,也可设置reverse = True 来降序排序。
def sorted(iterable: Iterable[_T], *,
key: Optional[callable[[_T], Any]] = ...,
reverse: bool = ...) --> List[_T]: ...
# iterable 序列
# key 可以用来计算的排序函数
# reverse 是否倒置
list1 = [5, -1, 3, 6, -7, 8, -11, 2]
list2 = ['apple', 'pig', 'monkey', 'money']
print(sorted(list1, key=abs))
# print out: [-1, 2, 3, 5, 6, -7, 8, -11]
# 匿名函数排序
print(sorted(list2, key=lambda x: len(x), reverse=True))
# print out: ['monkey', 'apple', 'money', 'pig']