ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Python函数式编程实战指南

Python函数式编程实战指南 # Python函数式编程实战指南 函数式编程是一种以函数为核心的编程范式强调纯函数、不可变数据和无副作用。 ## 一、map 批量转换 map(func, iterable) 会把函数应用到可迭代对象的每个元素上。 python prices [19.99, 5.49, 120.00] rounded list(map(lambda p: round(p, 2), prices)) print(rounded) # [19.99, 5.49, 120.0] ## 二、filter 筛选 filter(func, iterable) 只保留使函数返回 True 的元素。 python logs [{level: ERROR, msg: 连接失败}, {level: INFO, msg: 启动}] errors list(filter(lambda x: x[level] ERROR, logs)) print(errors) # [{level: ERROR, msg: 连接失败}] ## 三、reduce 累积计算 reduce 把二元函数依次应用到序列元素上折叠成单个结果。 python from functools import reduce nums [1, 2, 3, 4, 5] total reduce(lambda acc, x: acc x, nums) print(total) # 15 ## 小结 函数式编程让代码更简洁、更可测试。Python 虽不是纯函数式语言但掌握这些工具能让你的代码更优雅。
返回列表