""" 模块:python3 reduce().py 功能: 参考:https://www.runoob.com/note/26811 知识点: 1.reduce(...) reduce(function, sequence[, initial]) -> value 将两个参数的函数累积应用于序列的项,从左到右,以便将序列减少到单个值。 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). 如果存在初始值 initial,则将其放置在计算中序列的项之前,并在序列为空时充当默认值。 """ from functools import reduce def add(x, y): return x + y print(reduce(add, range(1, 101))) # 5050 print(reduce(add, range(1, 6))) # 15 print(reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])) # 15 initial = 0 print(reduce(add, range(1, 6), initial)) # 15 initial = 1 print(reduce(add, range(1, 6), initial)) # 16 # help(reduce)
python3 reduce().py
最新推荐文章于 2021-11-10 10:25:44 发布