zoukankan      html  css  js  c++  java
  • python中的lambda匿名函数和reduce、filter、map函数

    1 func=lambda x:x+1
    2 print(func(1))
    3 #2
    4 print(func(2))
    5 #3
    6 
    7 #以上lambda等同于以下函数
    8 def func(x):
    9     return(x+1)
    
    可以这样认为,lambda作为一个表达式,定义了一个匿名函数,上例的代码x为入口参数,x+1为函数体。
    在这里lambda简化了函数定义的书写形式,使代码更为简洁.但是使用函数的定义方式更为直观,易理解
    (此处在python自带idle演示:)
    
     1 from functools import reduce 
     2 foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
     3 
     4 print (list(filter(lambda x: x % 3 == 0, foo)))
     5 #[18, 9, 24, 12, 27]
     6 
     7 print (list(map(lambda x: x * 2 + 10, foo)))
     8 #[14, 46, 28, 54, 44, 58, 26, 34, 64]
     9 
    10 print (reduce(lambda x, y: x + y, foo))
    11 #139
    
    
    关于filter、map、reduce函数
    
     ·filter()函数
    filter()函数包括两个参数,分别是function和list。
    该函数根据function参数返回的结果是否为真来过滤list参数中的项,
    最后返回一个新列表,如下例所示:(此处在cmd命令行演示)
    >>>a=[1,2,3,4,5,6,7]
    >>>b=filter(lambda x:x>5, a)
    >>>print b
    >>>[6,7]
    
    ·map()函数
    map()的两个参数:前面是函数名,后面是一个列表或元组,也可以是两个列表或元组。
    其意义是把前面的函数依次作用在后面的列表或元组上,得到一个新的可迭代对象,其
    返回值为<map object at 0x01085570>
    >>>a=[1,2,3,4,5,6,7]
    >>>map(lambda x:x+3, a) #这里的a同上
    >>>[3,4,5,6,7,8,9,10]
    
    #另一个例子
    >>>a=[1,2,3]
    >>>b=[4,5,6]
    >>>map(lambda x,y:x+y, a,b)
    >>>[5,7,9]
    
     ·reduce()函数,使用前需要导入  from functools import reduce
    reduce 函数可以按照给定的方法把输入参数中上序列缩减为单个的值,具体的做法如下:
    首先从序列中去除头两个元素并把它传递到那个二元函数中去,求出一个值,再把这个加到序列中循环求下一个值,直到最后一个值 。
    >>>reduce(lambda x,y:x*y, [1,2,3,4,5]#((((1*2)*3)*4)*5 >>>120 >>>reduce(lambda x,y:x*y, [1,2,3], 10) >>>60 #((1*2)*3)*10
  • 相关阅读:
    Spring Boot (20) 拦截器
    Spring Boot (19) servlet、filter、listener
    Spring Boot (18) @Async异步
    Spring Boot (17) 发送邮件
    Spring Boot (16) logback和access日志
    Spring Boot (15) pom.xml设置
    Spring Boot (14) 数据源配置原理
    Spring Boot (13) druid监控
    Spring boot (12) tomcat jdbc连接池
    Spring Boot (11) mybatis 关联映射
  • 原文地址:https://www.cnblogs.com/znh8/p/9264711.html
Copyright © 2011-2022 走看看