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
    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    Vue对象提供的属性功能
    Vue快速入门
    Django-DRF(路由与扩展功能)
    Django-DRF(视图相关)
    Django-DRF(1)
    Django-Xadmin
    python 列表的append()和extend()
    map apply applymap
    pd.merge(), pd.concat()
    描述性分析与数据清洗 笔记
  • 原文地址:https://www.cnblogs.com/noahzn/p/4133249.html
Copyright © 2011-2022 走看看