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

猜你喜欢

转载自www.cnblogs.com/lzn-2018/p/10758102.html