您的位置:首页 > 编程语言 > Python开发

python进阶-函数式编程

2016-11-08 23:35 337 查看

Python

高阶函数

定义

高阶函数:能接受函数作为参数的函数

#计算25的开方和9的开方和
import math
def add(x, y, f):
return f(x) + f(y)

print(add(25, 9, math.sqrt))
#8.0


map()函数

map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回.

def function(x):
return x*x
list(map(function,[1,2,3,4]))
#[1, 4, 9, 16]


Note:注意:map()函数不改变原有的 list,而是返回一个新的 list.

reduce()函数

reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。

#计算2*4*5*7*12
from functools import reduce
def product(x, y):
return x * y
print(reduce(product, [2, 4, 5, 7, 12]))
#3360


Note:Python3已经移除了reduce 函数,我们可以引用functools模块来调用 reduce ()函数.

filter()函数

filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

def is_odd(x):
return x % 2 == 1

f1 = filter(is_odd, [1, 4, 5, 7, 8, 10, 11])
print(list(f1))
#[1, 5, 7, 11]


例子:埃氏筛法求质数

#构造一个从3开始的奇数序列
def _odd_iter():
n = 1
while True:
n = n + 2
yield n

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

def primes():
yield 2
it = _odd_iter();
while True:
n = next(it)
yield n
it = filter(_not_divisible(n), it)

for n in primes():
if n < 100:
print(n)
else:
break


sorted()函数

Python内置的 sorted()函数可对list进行排序.

l=sorted([, 4, -1, 5, 8, -9, -3])
print(l)
#[-9, -3, -1, 2, 4, 5, 8]


但 sorted()也是一个高阶函数,它可以接收一个比较函数来实现自定义排序,比较函数的定义是,传入两个待比较的元素 x, y,如果 x 应该排在 y 的前面,返回 -1,如果 x 应该排在 y 的后面,返回 1。如果 x 和 y 相等,返回 0。

sorted()函数默认是升序排列的,我们可以自己实现倒叙排列.

print(sorted([2, 4, -1, 5, 8, -9, -3],reverse=True))
#[8, 5, 4, 2, -1, -3, -9]


还可以按照绝对值进行排序

print(sorted([2, 4, -1, 5, 8, -9, -3], key=abs))
#[-1, 2, -3, 4, 5, 8, -9]


返回函数

Python的函数不但可以返回int、str、list、dict等数据类型,还可以返回函数.

def f():
print('call f()...')
def g():
print('call g()...')
return g
print(f())
#call f()...
#<function f.<locals>.g at 0x10981d1e0>
print(f()())
#call f()...
#call g()...


返回函数的作用可以把一些计算延
4000
迟.由于可以返回函数,我们在后续代码里就可以决定到底要不要调用该函数.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息