python学习笔记 map&&reduce

时间:2022-01-30 11:39:32

---恢复内容开始---

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上的,比如下面的求和

 tadd = reduce(add,range(6))
print (tadd)
tadd = reduce(add, [x for x in range(6) if x%2 != 0])
print (tadd)

reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

 # -*- coding: utf-8 -*-
"""
Spyder Editor This is a temporary script file.
"""
from functools import reduce
tadd = reduce(add,range(6))
print (tadd)
tadd = reduce(add, [x for x in range(6) if x%2 != 0])
print (tadd)
tadd = reduce(fn,[x for x in range(9) if x%2 != 0])
print (tadd)

3)对于一些版本的简化:

 from functools import reduce
def f(x):
return x*x def add(x1,x2):
return x1+x2
def fn(x1,x2):
return 10*x1+x2 def char2num(s):
return {'':0,'':1,'':2,'':3,'':4,'':5,'':6,'':7,'':8,'':9}[s] def str2int(s):
def char2num(s):
return {'':0,'':1,'':2,'':3,'':4,'':5,'':6,'':7,'':8,'':9}[s] def fn(x1,x2):
return 10*x1+x2
return reduce(fn,map(char2num,s))
def str2int_2(s):
return reduce(lambda x,y:x*10+y,map(char2num,s)) 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而是一个空的[] tadd = reduce(add,range(6))
print (tadd)
tadd = reduce(add, [x for x in range(6) if x%2 != 0])
print (tadd)
tadd = reduce(fn,[x for x in range(9) if x%2 != 0])
print (tadd)
print (reduce(fn,(map(char2num,''))))
print (str2int(''))
print (str2int_2(''))

---恢复内容结束---