zoukankan      html  css  js  c++  java
  • 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 函数运算,最后得到一个结果

  • 相关阅读:
    Struts2 HelloWorld_1
    Java Web JavaMail 邮件发送
    Struts2 ActionWildcard(通配符配置)约定优于配置
    Struts2 Action
    Struts2 struts2简介
    Struts2 ActionMethod DMI(动态方法调用)
    Java Web Servlet过滤器
    com学习笔记(2)基本的com接口QueryInterface的实现
    com学习笔记(4)动态链接
    silverlight Visifire图表转图片偷天换日的做法
  • 原文地址:https://www.cnblogs.com/tallme/p/11237580.html
Copyright © 2011-2022 走看看