python学习笔记 map&&reduce
---恢复内容开始---
1.map
1)map其实相当对吧运算符进行一个抽象,返回的是一个对象,但是这里不知道为什么不可以对一个map返回变量打印两次,难道是因为回收了?
def f(x): return x*x tmp = map(f,range(6)) tmps = map(str,range(6)) print (list(tmp)) #print (list(tmps)) print (type(range(6)))#range返回的就是range类型<class 'range'> print (set(tmps)) print(list(tmps))#此时的输出不在是range6的List而是一个空的[]
2)reduce 需要两个以上的参数才能使用,一般是作用域一个list上的,比如下面的求和
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 tadd = reduce(add,range(6)) 2 print (tadd) 3 tadd = reduce(add, [x for x in range(6) if x%2 != 0]) 4 print (tadd)
reduce
把一个函数作用在一个序列[x1, x2, x3, ...]
上,这个函数必须接收两个参数,reduce
把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # -*- coding: utf-8 -*- 2 """ 3 Spyder Editor 4 5 This is a temporary script file. 6 """ 7 from functools import reduce 8 tadd = reduce(add,range(6)) 9 print (tadd) 10 tadd = reduce(add, [x for x in range(6) if x%2 != 0]) 11 print (tadd) 12 tadd = reduce(fn,[x for x in range(9) if x%2 != 0]) 13 print (tadd)
3)对于一些版本的简化:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from functools import reduce 2 def f(x): 3 return x*x 4 5 def add(x1,x2): 6 return x1+x2 7 def fn(x1,x2): 8 return 10*x1+x2 9 10 def char2num(s): 11 return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[s] 12 13 def str2int(s): 14 def char2num(s): 15 return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[s] 16 17 def fn(x1,x2): 18 return 10*x1+x2 19 return reduce(fn,map(char2num,s)) 20 def str2int_2(s): 21 return reduce(lambda x,y:x*10+y,map(char2num,s)) 22 23 tmp = map(f,range(6)) 24 tmps = map(str,range(6)) 25 print (list(tmp)) 26 #print (list(tmps)) 27 print (type(range(6)))#range返回的就是range类型<class 'range'> 28 print (set(tmps)) 29 print(list(tmps))#此时的输出不在是range6的List而是一个空的[] 30 31 tadd = reduce(add,range(6)) 32 print (tadd) 33 tadd = reduce(add, [x for x in range(6) if x%2 != 0]) 34 print (tadd) 35 tadd = reduce(fn,[x for x in range(9) if x%2 != 0]) 36 print (tadd) 37 print (reduce(fn,(map(char2num,'213')))) 38 print (str2int('1231')) 39 print (str2int_2('321'))
---恢复内容结束---