Python之高阶函数(functools)

# 高阶函数 functools
import functools

# 遍历序列元素为参数依次应用到函数中,最终返回累计的结果
n = functools.reduce(lambda x, y: x + y, [1, 2, 3, 4, 5], 10)  # 等价于((((1+2)+3)+4)+5)+10
print(n)  # 25

# 偏函数:对函数进行二次包装,从而简化操作,作用类似Java重载
square = functools.partial(pow, exp=2)  # 指定为平方,简化入参
print(square(2))  # 4

# 遍历处理(Python原生函数)
mapped = map(lambda x: ord(x) + 10, "hello")
print(list(mapped))  # [114, 111, 118, 118, 121]

# 遍历后感觉条件过滤(Python原生函数)
li = filter(lambda x: x % 2, range(10))
print(list(li))  # [1, 3, 5, 7, 9]

 

posted @ 2023-01-29 00:47  星瑞  阅读(76)  评论(0编辑  收藏  举报