test页首

python语法糖记录

reduce

对可迭代对象进行累积操作
https://www.runoob.com/python/python-func-reduce.html
注意:Python3.x reduce() 已经被移到 functools 模块里,如果我们要使用,需要引入 functools 模块来调用 reduce() 函数:
` from functools import reduce
reduce(function, iterable[, initializer])
function -- 函数,有两个参数
iterable -- 可迭代对象
initializer -- 可选,初始参数

def add(x, y) :            # 两数相加
    return x + y
sum1 = reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数
posted @ 2022-09-21 19:55  开饭了没  阅读(25)  评论(0)    收藏  举报

test页脚