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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值