Python之reduce函数使用示例

#!/usr/bin/env python
# -*- coding:utf8 -*-

'''reduce:处理一个序列,然后把序列进行合并操作'''

###在python中没有reduce函数,所以需要导入它(去掉前面的注释符即可)
#from functools import  reduce

def reduce_test(f,array,i = None):
    if i is None:
        tmp = array.pop(0)
    else:
        tmp = i
    for num in array:
        tmp = f(tmp,num)
    return tmp

num = [1,2,3,4,5]
'''将数组里的数字全部乘起来,i是对所得值乘以i'''
print(reduce_test(lambda x,y:x*y,num,10))

print()
#reduce函数
from functools import  reduce

num = [1,23,43,456,42]
'''将数组内的所有值加起来,i是对所得值加上i'''
print(reduce(lambda x,y:x+y,num,10))
print(reduce(lambda x,y:x+y,num))

==>

1200

575
565

posted @ 2019-04-23 18:28  Jony-2018  阅读(352)  评论(0编辑  收藏  举报