Python个人笔记-函数式编程

函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数。

Python对函数式编程提供部分支持。由于Python允许使用变量,因此,Python不是纯函数式编程语言。

高阶函数

-变量可以指向函数

-函数名也是变量

-传入函数

函数可以接收另一个函数作为参数,这种函数就称之为高阶函数,eg:

def add(x, y, f):
    return f(x) + f(y)

map/reduce

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

def f(x):
    return x * x
    
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
list(r) #iteration是惰性序列,通过list函数把整个序列都计算出来并返回一个list
[1, 4, 9, 16, 25, 36, 49, 64, 81]

再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4

如果把序列[1,3,5,7,9]变换成整数13579,使用reduce:

from functools import reduce
def fn(x, y):
    return x * 10 + y



reduce(fn, [1,3,5,7,9])
13579

接下来将map与reduce结合起来:

>>> from functools import reduce
>>> def fn(x, y):
...     return x * 10 + y
...
>>> def char2num(s):
...     digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
...     return digits[s]
...
>>> reduce(fn, map(char2num, '13579'))
13579

将这个str→int整合成一个函数:

from functools import reduce

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def str2int(s):
    def fn(x, y):
        return x * 10 + y
    def char2num(s):
        return DIGITS[s]
    return reduce(fn, map(char2num, s))

filter

filter()函数接收一个函数和一个序列,把传入的函数依次作用于每个元素,根据返回值是true或false来决定保留还是丢弃该元素。eg:

def is_odd(n):
    return n % 2 == 1
    
list(filter(is_odd, [1,2,3,4,5]))

def not_empty(s):
    return s and s.strip()
#str.strip()的作用是把字符串的头和尾的空格,以及位于头尾的\n \t之类给删掉

list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))
# 结果: ['A', 'B', 'C']
  • 用filter求素数:
def _odd_iter(): # 构造从3开始的奇数序列
    n = 1
    while True:
        n = n + 2
        yield n

def _not_divisible(n): # 筛选函数
    return lambda x: x % n > 0

def primes():
    yiled 2
    it = _odd_iter() # 初始序列
    while True:
        n = next(it) # 返回序列的第一个数
        yiled n
        it = filter(_not_divisible(n), it) # 构造新序列


# 打印1000以内的素数:
for n in primes():
    if n < 1000:
        print(n)
    else:
        break

sorted

sorted()为Python内置的排序函数。sorted也是高阶函数,它可以接收一个key函数,将此函数作用到list的每一个元素上,再根据key函数返回的结果进行排序。若需要反向排序,可传入第三个参数reverse=True

返回函数

函数可作为高阶函数的结果值返回。“闭包(Closure)”是在一个函数中又定义一个函数,内部函数可以引用外部函数的参数和局部变量,当外部函数将内部函数返回时,相关参数和变量都保存在这个返回的函数中。

返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量。

匿名函数lambda

在传入函数时,有时无需显式地定义函数,直接传入匿名函数更方便,比如lambda x: x * x实际上就是

def f(x):
    return x * x

装饰器

Python装饰器本质上就是一个函数,他可以让其他函数在不需要任何代码变动的前提下增加额外的功能,装饰器的返回值也是一个函数对象。以为函数添加计时功能为例:

import time

def decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        func()
        end_time = time.time()
        print(end_time - start_time)
    return wrapper


@decorator
def func():
    time.sleep(0.8)
    
    
    
func() #函数调用
# 输出:0.800644397735595

@decorator这个语法相当于执行func=decorator(func),为func函数装饰并返回。

偏函数

Python的functools模块提供了偏函数。利用functools.partial,我们可以把一个函数的某些参数固定住,返回一个新函数,调用这个新函数会更简单。eg:

import functools

int2 = functools.partial(int, base=2)

int2('1000000')
#输出64

上面的新函数仅仅把base参数重新设定默认值为2,但也可以在函数调用时传入其他值,如int2('1000000', base=10)

最后,创建偏函数时,实际上可接收函数对象、*args和**kw这三个参数,当传入int2 = functools.partial(int, base=2),固定了base 的参数,也就是int2('10010'),这相当于kw = {'base': 2}, int('10010', **kw)。

当传入:max2 = functools.partial(max, 10)

实际上就把10当做*args的一部分自动加到左边,也就是:max2(5,6,7),相当于:

args = (10, 5, 6, 7)
max(*args)

你可能感兴趣的:(Python个人笔记-函数式编程)