map
map函数根据提供的函数对指定的序列做映射,定义:
map(function, sequence[,sequence,...])--->list
例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个)
例2
>>> map(lambda x,y:x+y, [1, 2], [1, 2]) [2, 4] >>> map(lambda x,y:x+y, [1, 2], (1,2)) [2, 4]
例3
>>> 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)会报错。
例4
上面例子中只给了lambda,还可以用普通的函数
>>> 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]
例5
如果没有给定,就类似于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函数对指定的序列进行过滤操作。定义:
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函数会对参数序列中元素进行累积。定义:
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
编程中提到的 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))