map() 函数的功能:
map(f, [x1,x2,x3]) = [f(x1), f(x2), f(x3)]
def f(x): return x*x a = map(f, [1, 2, 3, 4, 5]) b = map(f, (6, 7, 8, 9)) print a print b # [1, 4, 9, 16, 25] # [36, 49, 64, 81] # a = map(f, 1,2,3,4,5,6,7) # print a # Traceback (most recent call last): # File "C:/workplace/SVC/DiskVideoTask/modules/test_mapReduce.py", line 8, in <module> # a = map(f, 1,2,3,4,5,6,7) # TypeError: argument 2 to map() must support iteration
reduce()的用法:
reduce(f, [x1, x2, x3]) = f(f(f(x1,x2),x3),x4).
def add(x,y): return x+y print reduce(add,[1,2,3,4,5]) # 15 def str2int(s): def fn(x,y): return x * 10 + y def char2num(s): return {‘0‘:0, ‘1‘:1, ‘2‘:2, ‘3‘:3, ‘4‘:4, ‘5‘:5, ‘6‘:6, ‘7‘:7, ‘8‘:8,‘9‘:9 }[s] return reduce(fn,map(char2num,s)) print str2int(‘9876‘) # 9876
原文:http://www.cnblogs.com/haoshine/p/5098088.html