同事问我python里,比如一个列表:

a = ['1', '2', '3']

如何变成:

b = ['1x', '2x', '3x']

好吧,果断不知道…原来pthon中有map函数,查看帮助文档:

map(...)
map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).

该函数可以对每一个元素都进行function处理,并返回一个列表。

因此和lambda一起使用就能很方便地达到目的,完整代码如下:

>>> a = ['1', '2', '3']
>>> b = map(lambda a : a +'x' , a)
>>> b
['1x', '2x', '3x']

再来说说lambda函数,lambda函数类似于定义一个函数,但是没有return,方便简洁。例如上述的代码,等同于定义一个函数,有一变量a,与字符x做连接。利用lambda函数甚至不用写函数名,如:

>>> (lambda x : x+3)(2)
5

真是太方便啦!但是可阅读性有点下降哦~

最新文章

  1. SQL分页查询的几种方式
  2. Android项目实战(十三):浅谈EventBus
  3. git push命令
  4. Android消息机制入门
  5. HDU 1548 (最基础的BFS了) A strange lift
  6. 转】Mahout分步式程序开发 聚类Kmeans
  7. 使用vhd灌装系统——测试系统专用
  8. COCOS2DX2.2.2 创建CCEditBox输入框架实现文本及密码输入
  9. Linux Systemd——在RHEL/CentOS 7中启动/停止/重启服务
  10. 0x3f3f3f3f...编程中无穷大常量的设置技巧
  11. JSCapture实现屏幕捕捉
  12. 3407: [Usaco2009 Oct]Bessie's Weight Problem 贝茜的体重问题
  13. Selenium2Lib库之鼠标事件常用关键字实战
  14. 数据库原理 - 序列4 - 事务是如何实现的? - Redo Log解析(续)
  15. Windows10家庭版如何升级至Windows10专业版
  16. Vue实现购物车小球动画
  17. 【JavaScript 6连载】六、认识原型
  18. hdu3518
  19. Azure 中的虚拟网络和虚拟机
  20. Androidstudio安装问题

热门文章

  1. myeclipse svn
  2. app启动其他应用
  3. 快速设计一个简单的WPF串口上位机
  4. history对象back()、forward()、go()
  5. 覆盖equals的时候总要覆盖hashCode
  6. 如何判断Fragment是否对用户可见
  7. Java基础知识强化之集合框架笔记46:Set集合之TreeSet存储自定义对象并遍历练习2(自然排序:Comparable)
  8. Rouh set 入门知识2(基础定义篇)
  9. 发布MVC IIS 报错未能加载文件或程序集“System.Web.Http.WebHost
  10. 详解SQL Server 2005 Express下的事件探查器