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
    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    python3 基础数据类型之列表及其操作方法
    python3 逻辑运算符
    python3 内置函数
    python3 装饰器
    python3 变量作用域
    python3 参数以及函数的传参
    python3 函数基础
    洛谷P3379倍增LCA
    洛谷P3375KMP字符串匹配
    洛谷P2613有理数取余
  • 原文地址:https://www.cnblogs.com/noahzn/p/4133249.html
Copyright © 2011-2022 走看看