zoukankan      html  css  js  c++  java
  • map和lambda

    同事问我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

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

    作者:Noah Zhang
    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    工作中,怎么做好规范
    每日一链
    模仿电子商务垂直菜单
    电脑不同的分辨率自适应显示
    怎样成为一位合格的程序员
    巅峰极客线上第一场ctf——RE
    恶意代码分析常见Windows函数
    巅峰极客线上第二场部分ctf
    恶意代码分析:虚拟网络环境配置
    0ctf2017 pwn babyheap
  • 原文地址:https://www.cnblogs.com/noahzn/p/4133249.html
Copyright © 2011-2022 走看看