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

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

posted on 2014-07-30 15:15  Noah.Zhang  阅读(535)  评论(0编辑  收藏  举报

导航