Python 函数式编程

x33g5p2x  于2022-07-13 转载在 Python  
字(1.0k)|赞(0)|评价(0)|浏览(159)

1 介绍

https://docs.python.org/zh-cn/3/howto/functional.html

函数式 编程将一个问题分解成一系列函数。

理想情况下,函数只接受输入并输出结果,对一个给定的输入也不会有英系那个输出内部状态。著名的函数式语言有ML家族和Haskell。

2 高阶函数

2.1 map/reduce

Python内建了map()reduce函数。
该函数的思想同Google发布的“MapReduce: Simplified Data Processing on Large Clusters”相同。

2.1.1 map方法

eg. f(x)=x^2

(1)用map方式实现

def f(x):
    return x * x

r = map(f, [1, 2, 3])
print(list(r))  # 输出:[1, 4, 9]

(2)传统方式
这种方法将 f(x)作用到了list的每一个元素,结果在新的list

def f(x):
    return x * x

L = []
for n in [1, 2, 3]:
    L.append(f(n))
print(L)  # 输出:[1, 4, 9]

eg. 将list所有数字转为字符串

print(list(map(str, [1, 2, 3])))  
# 输出:['1', '2', '3']
2.1.1 reduce方法

reduce 把一个函数作用在以下序列 [x1, x2, x3,…] 上,这个函数必须介绍2个参数, reduce 把结果继续和序列的下一个元素做积累计算,其效果为

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

序列求和

# 1 reduce方法
from functools import reduce

def add(x, y):
    print(x, y)
    return x + y
    # 输出
    # 1 2
    # 3 3

print(reduce(add, [1, 2, 3]))
# 输出:6

# 2 直接sum方法
print(sum([1, 2, 3]))

把序列[1, 3, 5, 7, 9]变换成整数13579

# 把序列[1, 3, 5, 7, 9]变换成整数13579
from functools import reduce

def fn(x, y):
    return x * 10 + y

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

参考地址:
https://docs.python.org/zh-cn/3/howto/functional.html
https://www.liaoxuefeng.com/wiki/1016959663602400/1017328525009056

相关文章