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

posted @ 2017-04-24 00:03  C/C++/Python/Java  阅读(731)  评论(0编辑  收藏  举报