鱼C论坛

 找回密码
 立即注册
查看: 2167|回复: 0

[技术交流] 《零基础学习Python》21函数: lamda表达式+filter()+map()

[复制链接]
发表于 2017-8-29 21:12:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 只为 于 2017-8-29 21:48 编辑

1、lambda表达式
  1. >>> g = lambda x : 2 * x +1
  2. >>> g(3)
  3. 7
  4. >>> type(g)
  5. <class 'function'>
  6. >>> lambda x : 2 * x +1
  7. <function <lambda> at 0x00000000034F3D08>
复制代码


2、lambda表达式的作用
1)python写一些执行代码是,使用lambda可以省下定义函数过程
2)对于一些比较抽象并且整个程序执行下来只需要调用一两次的函数,使用lambda不需要考虑命名的问题
3)简化代码的可读性,不用阅读函数时跳到def定义部分

3、两个牛逼的BIF
1)filter() 过滤器:过滤掉加的
查看帮助:help(filter)
  1. >>> help(filter)
  2. Help on class filter in module builtins:

  3. class filter(object)
  4. |  filter(function or None, iterable) --> filter object
  5. |  
  6. |  Return an iterator yielding those items of iterable for which function(item)
  7. |  is true. If function is None, return the items that are true.
复制代码


eg.
  1. >>> filter(None,[1,True,False,'',{},None,[]])
  2. <filter object at 0x00000000034F1B70>
  3. >>> list(filter(None,[1,True,False,'',{},None,[]]))
  4. [1, True]
复制代码

  1. >>> list(filter(lambda x : x%2,range(10)))
  2. [1, 3, 5, 7, 9]
复制代码


2)map() 映射
  1. >>> help(map)
  2. Help on class map in module builtins:

  3. class map(object)
  4. |  map(func, *iterables) --> map object
  5. |  
  6. |  Make an iterator that computes the function using arguments from
  7. |  each of the iterables.  Stops when the shortest iterable is exhausted.
  8. >>> list(map(lambda x : x *2, range(9)))
  9. [0, 2, 4, 6, 8, 10, 12, 14, 16]
复制代码


评分

参与人数 1鱼币 +3 收起 理由
小甲鱼 + 3

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-23 15:54

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表