map#
map(function, sequence[, sequence, ...]) -> list
说明:
对sequence中的每一项分别执行function,输出结果组成list
>>> map(lambda x: x*x, range(5))
[0, 1, 4, 9, 16]
想要输入多个序列,需要支持多个参数的函数,注意的是各序列的长度必须一样,否则报错:
>>> map(lambda x,y:x+y,['c','b','a'],['a','b','c'])
['ca', 'bb', 'ac']
>>>
>>>
>>> map(lambda x,y:x+y,['c','b','a'],['a','b','c','d'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
filter#
filter(function or None, sequence) -> list, tuple, or string
说明:
对sequence中的item依次执行function(item),将执行结果为True(!=0)的item组成一个List/String/Tuple(取决于sequence的类型)返回,进行过滤。
>>> filter(lambda x: x%2, range(5))
[1, 3]
>>>
>>> filter(lambda x: x%2, (2,3,4,5,6))
(3, 5)
>>>
>>> filter(lambda x: x!='z', 'zhouzhou')
'houhou'
reduce#
reduce(function, sequence[, initial]) -> value
说明:
对sequence中的item顺序迭代调用function,函数必须要有2个参数。要是有第3个参数,则表示初始值,可以继续调用初始值,返回一个值。
>>> reduce(lambda x,y:x+y,range(5),2)
12
>>> reduce(lambda x,y:x+y,range(5))
10
练习:5!+4!+3!+2!+1!
>>> def calc(n):
... l=[]
... for i in map(lambda x: x+1, range(n)):
... ret = reduce(lambda x,y:x*y,map(lambda x: x+1, range(i)))
... l.append(ret)
... return l
...
>>> reduce(lambda x,y : x+y,calc(5))
153