- >>> def myfunction(a,b):
- ... return a*b
- ...
- >>> mylist = [1,2,3,4,5]
- >>> print reduce(myfunction, mylist)
- 120
- #上面的代码相当于:
- >>>print ((((1*2)*3)*4)*5)
- 120
- #也可以直接使用操作符模块来替代函数
- >>> import operator
- >>> mylist = [1,2,3,4,5]
- >>> print reduce(operator.mul, mylist)
- 120
- >>> print reduce(operator.add, mylist)
- 15
- #该片段来自于http://www.codesnippet.cn/detail/150120131659.html
来源: http://www.codesnippet.cn/detail/150120131659.html