Python语言的高级特性
函数式编程¶
- 基于lambda演算3的一种编程方式
- 程序中只有函数
- 函数可以作为参数,同样可以作为返回值
- 纯函数式编程语言:LISP,Haskell
- python函数式编程只是借鉴函数式编程的一些特点,可以理解为一半函数式编程一半Python
- 内容
- 高阶函数
- 返回函数
- 匿名函数
- 装饰器
- 偏函数
lambda表达式
- 函数: 最大程度复用代码
- 存在问题:函数很小,很短,会造成啰嗦
- 如果函数被调用次数少,则会造成浪费
- 对于阅读者来说,造成阅读流程中断
- lambda表达式(匿名函数):
- 一个表达式,函数体相对简单
- 不是一个代码块,仅仅是一个表达式
- 可以有参数,有多个参数也可以,用逗号隔开
- 用法:
- 以lambda开头
- 紧跟一定的参数(如果有的话)
- 参数后用冒号与表达式分开
- 只是一个表达式,所以没有return
In [11]:
#lambda例子---一个参数
stm1 = lambda m : m * 100
#使用时与函数调用一模一样
stm1(20)
Out[11]:
2000
In [10]:
#多参
stm2 = lambda x,y,z : x*29+y*30-z*29
stm2(33,33,33)
Out[10]:
990
高阶函数
- 把函数作为参数使用的函数,叫做高阶函数
- 函数名称是变量,可以被当做参数传入另一函数
In [12]:
#函数名称可以作为变量
def funA ():
print('Hello , funA')
funB = funA
funB()
Hello , funA
In [22]:
#高阶函数举例
def funA(n):
return n*100
#把函数funA乘以3
def funB(n):
return funA(n)*3
#乘以一个数的300倍
print (funB(4))
#高阶函数
def funA(n):
return n*100
def funC(n,f):
return f(n)*3
print(funC(9,funA))
1200 2700
系统高阶函数
- 原意就是映射,把集合或者列表的元素,每一个元素都按一定的规则进行操作,生成一个新的列表或集合
- map函数是系统提供的具有映射功能的函数,返回值是一个迭代对象
- map(函数,可迭代内容)
In [26]:
#将一个列表中的每一个元素乘以10
l1 = [i for i in range(10)]
print(l1)
l2 = []
for i in l1:
l2.append(i*10)
print(l2)
#map 举例
l1 = [i for i in range(10)]
def mulTen(n):
return n *10
l3 = map(mulTen,l1)#第一个参数为函数,第二个参数为可迭代内容
print(l3)
print(type(l3))#使用map函数后类型变为map
for i in l3:
print(i,end=' ')#凡是可迭代的都可以用for循环进行访问(map类型为可迭代的)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] <map object at 0x7f4e780c0e10> <class 'map'> 0 10 20 30 40 50 60 70 80 90
reduce
- 原意是归并,缩减
- 把可迭代的对象最后归并成一个结果
- 对于作为参数的函数要求:必须有两个参数,必须有返回值
- reduce需要导入functools包
-
语法
-
reduce() 函数语法:
reduce(function, iterable[, initializer])
-
- 参数
- function -- 函数,有两个参数
- iterable -- 可迭代对象
- initializer -- 可选,初始参数
- 返回值
- 返回函数计算结果。
In [34]:
#reduce实例
from functools import reduce
#定义一个操作函数
def Addm(m,n):
return m+n
res = reduce (Addm,[1,2,3,4,5])
print(res)
help(reduce)
15 Help on built-in function reduce in module _functools: reduce(...) reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.