The study of map() and reduce() function in Python(20170913)
来源:互联网 发布:plc编程梯形图实例 编辑:程序博客网 时间:2024/04/29 22:53
The study of map() and reduce() function in Python(20170913)
the map() function recieve 2 parameters,
one is a function, another is a Iterable
and than return a result as a Iterator
def f(x):
return x*x*x
r = map(f,[1,2,3,4,5,6,7])
print(list(r))
1 8 27 64 125 216 343
the Iterator is a 惰性序列
print(list(map(str,[1,2,3,4,5,6,7])))
[‘1’,’2’,’3’,’4’,’5’,’6’,’7’]
map(function,[list])
reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, …]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
reduce(f,[x1,x2,x3,x4]) = f(f(f(x1,x2),x3),x4)
example
from functools import reduce
def add(x,y):
return x + y
print(reduce(add,[1,3,5,7,9])) # 25
the function can change the str to int
def char2int(s):
return {‘0’:0,’1’:1,’2’:2,’3’:3}[s]
def fn(x,y):
return x*10+y
print(reduce(fn,map(char2int,’0123’)))
123
exercise1
from functools import reduce
def normalize(name):
return name[0].upper()+name[1:].lower()
l1 = [‘adam’,’yuhanyu’]
l2 = list(map(normalize,l1))
print(l2)
Adam,Yuhanyu
exercise3
from functools import reduce
def str2float(s):
n = s.index(‘.’)
return float(s[:n])+float(‘0.’+s[n+1:])
print(str2float(‘123.456’))
123.456
exercise
from functools import reduce
def prod(l):
return reduce(lambda x,y:x*y,l)
print(prod([3,4,5,6]))
360 = 3*4*5*6
- The study of map() and reduce() function in Python(20170913)
- The study of Higher-order function in Python(20170913)
- the built-in function of reduce in python
- The study of parameter of function in Python(20170908)
- The study of recursive function in Python(20170910)
- Map and Reduce (in python)
- The study of Class and Instance in Python(20170918)
- The study of how to define a function in Python(20170907)
- The study of loop in Python(20170906)
- The study of slice in Python(20170911)
- The study of literation in Python(20170911)
- The study of generator in Python(20170912)
- The study of list ,tuple and conditional statement in Python(20170905)
- the argument of function in python
- The study of calling fuction in Python(20170907)
- The study of List Comprehensions in Python(20170911)
- The study of iterator in Python(20170912)
- The study of access restriction in Python(20170920) 访问限制
- maven安装jar包到本地仓库
- chrome控制台console方法表
- android 解析包错误
- 极光效果通发布重定向app拉活服务,为头部app提升DAU
- 配置Vue开发环境
- The study of map() and reduce() function in Python(20170913)
- java7 invokedynamic命令深入研究
- Java笔记(3)
- 让机器读懂用户——大数据中的用户画像
- MySQL数据库索引的基础操作
- 移动app测试中出现bug漏测的原因分析
- 第一周9.13
- hrbust 1283 又见皇后
- 单例模式必须具备的3个元素