python reduce()函数使用

reduce()的使用方法形如reduce(function, iterable[, initializer]),它的形式和map()函数一样。不过参数f(x)必须有两个参数,initializer是可选的。

请看实例:(注意在Python3中reduce不再是内置函数,而是集成到了functools中,需要导入)

 

# -*- coding: utf-8 -*-
#coding=utf-8
'''
@author: tomcat
@license: (C) Copyright 2017-2019, Personal exclusive right.
@contact: liliang07@yungengxin.com
@software: coding
@file: map.py
@time: 2019/7/24 11:53
'''
from  functools import  reduce
'''

利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
'''
def normalize(name):
    name = name[0].upper() + name[1:].lower()
    return name
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
print(tuple(map(str, ["aa", 2, 3, 4, 5, 6, 7, 8, 9])))
print(list(map(str, ["aa", 2, 3, 4, 5, 6, 7, 8, 9])))
'''
两个数相加
'''
def add(x,y):
    return  x+y
res=reduce(add,[1,2,3,4,5])
res1=reduce(lambda x, y: x+y, [1,2,3,4,5])
print(res)
print(res1)

  原理:

函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果

原文地址:https://www.cnblogs.com/tallme/p/11237580.html