首页 > 代码库 > python学习笔记 -- reduce合并减少

python学习笔记 -- reduce合并减少

‘‘‘合并减少‘‘‘
import functools


lst = [1,2,3,4,5]
add = functools.reduce(lambda x,y: x + y, lst)
print(‘add = %d‘ % add) #add = 15

mul = functools.reduce(lambda x,y: x*y, lst)
print(‘mul = %d‘ % mul) #mul = 120


import operator
add2 = functools.reduce(operator.add, lst)
print(‘add2 = {}‘.format(add2)) #add2 = 15

mul2 = functools.reduce(operator.mul, lst)
print(‘mul2 = {}‘.format(mul2)) #mul2 = 120

打印结果:
add = 15
mul = 120
add2 = 15
mul2 = 120

python学习笔记 -- reduce合并减少