Python中如何将以下迭代代码改为函数式编程风格?

Python 代码

def parse(self, data):
    tmp = data
    # funcs is a callable function iterator
    for func in funcs:
        tmp = func(tmp)
    return tmp

Python中如何将以下迭代代码改为函数式编程风格?
6 回复

reduce(lamda x, y: y(x), funcs, data)


要改成函数式风格,主要用map()filter()reduce()。比如处理列表时,map()替代循环转换,filter()替代条件筛选。看个具体例子:

from functools import reduce

# 原始迭代代码
numbers = [1, 2, 3, 4, 5]
result = []
for num in numbers:
    if num % 2 == 0:
        result.append(num * 2)

# 函数式改写
result = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, numbers)))

更清晰的话可以用列表推导式,它也算函数式风格:

result = [x * 2 for x in numbers if x % 2 == 0]

复杂点的情况,比如求偶数的乘积:

from functools import reduce

product = reduce(lambda x, y: x * y, filter(lambda x: x % 2 == 0, numbers), 1)

核心就是避免直接修改状态,用纯函数和表达式。列表推导式通常更Pythonic。

一句话建议:用map/filter/reduce或列表推导式替代循环。

递归实现 判断 funcs

funs = [(+1),(*2),(subtract 3)]
f = foldr (flip (.)) id funs
f 1

您这不是 Python 代码呀

(fold-left (λ (tmp, func) (func tmp)) data funcs)

回到顶部