zoukankan      html  css  js  c++  java
  • Python之reduce

    # -*- coding: utf-8 -*-
    #python 27
    #xiaodeng
    #Python之reduce
    #http://python.jobbole.com/82597/
    
    
    #1)reduce语法格式:
    '''
    reduce(...)
        reduce(function, sequence[, initial]) -> value
        
        Apply a function of two arguments cumulatively to the items of a sequence,
        from left to right, so as to reduce the sequence to a single value.
        For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
        ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
        of the sequence in the calculation, and serves as a default when the
        sequence is empty.
    '''
    #function:函数名,函数自身能接收两个参数,决定了sequence中元素的作用方式,是乘法还是除法等等
    #sequence:序列
    #initial:累积初始值;如果给出initial, 则第一次传递initial和sequence的第一个元素给function.
    
    
    
    #2)reduce具体用法案例
    n=4
    print reduce(lambda x,y:x*y,range(1,n+1))#24
    
    
    #等价于:
    k=range(1,n+1)
    def func(x,y):
        return x*y
    
    print reduce(func,k)#24
    
    
    #添加第三个参数
    n=4
    print reduce(lambda x,y:x*y,range(1,n+1),n)#96
    #4*1*2*3*4
    #首先将第三个参数n和range(1,n+1)的第一个参数传递给func函数。
  • 相关阅读:
    java_hibernate 框架4
    java_hibernate 框架3
    java 基础 动态代理
    java_hibernate 框架2
    nginx配置反向代理实现负载均衡 小记
    mysql报错2059
    docker安装php容器小记
    docker安装nginx容器小记
    linux php添加pdo_mysql扩展
    linux php添加openssl扩展
  • 原文地址:https://www.cnblogs.com/dengyg200891/p/4944716.html
Copyright © 2011-2022 走看看