1、map
map(function,sequence) calls function(item) for each of the sequence’s items and returns alist of
the return values.
map對序列中的每一個items調用function(items),並返回一個列表。
>>> defcube(x): return x*x*x
...
>>>map(cube, range(1,5))
[1, 8, 27, 64]
>>>map(lambda x:x+5, range(1,8))
[6, 7, 8, 9, 10, 11,12]
2、reduce
reduce(function,sequence) returns a single value constructed by calling the binary functionfunction
on the first twoitems of the sequence, then on the result and the next item, and so on.
對sequence中的item順序迭代調用function,函數必須要有2個參數。要是有第3個參數,則表示初始值,可以繼續調用初始值,返回一個值。
>>> defadd(x,y): return x+y
...
>>>reduce(add, range(1, 11))
55
#1+2+3+4+5+6+7+8+9+10
>>>reduce(add, range(1, 11),10)
65
#初始值爲10,10 +1+2+3+4+5+6+7+8+9+10
>>> defmulti(x,y): return x*y
...
>>>
>>>reduce(multi, range(2,5)) # 2*3*4
24
>>>reduce(multi, range(2,5),5) # 5*2*3*4
120
>>>reduce(lambda x,y:x*y, range(2,8))
5040
>>>reduce(lambda x,y:x*y, range(2,8),10)
50400
3、filter
filter(function,sequence) returns a sequence consisting of those items from the sequence forwhich
function(item) istrue. If sequence is a str, unicode or tuple, the result will be of the sametype;
otherwise, it isalways a list.
對sequence中的item依次執行function(item),將執行結果爲True(!=0)的item組成一個List/String/Tuple(取決於sequence的類型)返回,False則退出(0),進行過濾。
>>> deff(x): return x % 3 == 0 or x % 5 == 0
...
>>>filter(f, range(2, 25))
[3, 5, 6, 9, 10, 12,15, 18, 20, 21, 24]
>>>filter(lambda x:x%2, range(10))
[1, 3, 5, 7, 9]
4、實現5!+4!+3!+2!+1!
def add_fact(n):
empty_list=[]
for i in map(lambda x:x+1, range(n)):
temp=reduce(lambda x,y:x*y,range(1,i+1))
empty_list.append(temp)
return empty_list
>>> importadd_fact
>>>a=add_fact
>>>reduce(lambda x,y:x+y, a.add_fact(5))
153