map函数根据提供的函数对指定的序列作映射,定义:
map(function, sequence[,sequence,...])--->listpython
例1编程
>>> map(lambda x:x+2, [1, 2, 3]) [3, 4, 5] >>> map(lambda x:x+2, (1, 2, 3)) [3, 4, 5] >>> map(lambda x:x+2, [1, 2], [1, 2]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: <lambda>() takes exactly 1 argument (2 given)
最后这个例子说lambda函数须要传2个参数(由于后面的列表是2个)函数
例2post
>>> map(lambda x,y:x+y, [1, 2], [1, 2]) [2, 4] >>> map(lambda x,y:x+y, [1, 2], (1,2)) [2, 4]
例3url
>>> a [{'type': 2, 'ID': 1}, {'type': 4, 'ID': 2}, {'ID': 3}] >>> map(lambda x:x['ID'], a) [1, 2, 3] >>> map(lambda x:x['type'], a) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> KeyError: 'type'
例子说明,若是其中的一个键不存在({'ID':3}不存在type)会报错。spa
例4code
上面例子中只给了lambda,还能够用普通的函数htm
>>> def func2(x, y): ... return x+y ... >>> map(func2, [1, 2, 3], [3, 2, 1]) [4, 4, 4] >>> >>> def func1(x): ... return x**2 ... >>> map(func1, [1, 2, 3]) [1, 4, 9]
例5blog
若是没有给定,就相似于zip函数了
>>> map(None, [1, 2, 3, 4], [1, 2, 3, 4]) [(1, 1), (2, 2), (3, 3), (4, 4)] >>> map(None, [1, 2, 3, 4], [1, 2, 3, 4,5]) [(1, 1), (2, 2), (3, 3), (4, 4), (None, 5)] >>> map(None, [1, 2, 3, 4], [1, 2, 3, 4,5], [1, 2, 3]) [(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, None), (None, 5, None)]
不过与zip不一样
>>> zip([1, 2, 3, 4], [1, 2, 3, 4,5], [1, 2, 3]) [(1, 1, 1), (2, 2, 2), (3, 3, 3)]
filter函数对指定的序列进行过滤操做。定义:
filter(function or None, sequence) -> list, tuple, or string
例1
>>> filter(lambda x:x%2==1, [1, 2, 3]) [1, 3] >>> filter(lambda x:x%2==1, (1, 2, 3)) (1, 3)
reduce函数会对参数序列中元素进行累积。定义:
reduce(function, sequence[, initial]) -> value
注:function必须是有2个参数的函数
例1
>>> reduce(lambda x, y:x+y, [1,2,3,4]) 10 >>> reduce(lambda x, y:x+y, [1,2,3,4], 10) 20
若是没有initial参数,这么算:(((1+2)+3)+4)
若是有initial参数,这么算: ((((10+1)+2)+3)+4)
编程中提到的 lambda 表达式,一般是在须要一个函数,可是又不想费神去命名一个函数的场合下使用,也就是指匿名函数。
举例对比(列表中的元素平方):
>>> map(lambda x:x*x, range(5)) [0, 1, 4, 9, 16] >>> def sq(x): ... return x * x ... >>> map(sq, range(5)) [0, 1, 4, 9, 16]
map(lambda x:x*x, range(5))