Python学习札记(二十一) 函数式编程2 map/reduce
参考:map/reduce
Note
1.map():map()函数接收两个参数,一个是函数,一个是Iterable。map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
#!/usr/bin/env python3
def f(x) :
return x*x
l = map(f, [1, 2, 3, 4, 5, 6, 7])
print(list(l))
sh-3.2# ./map1.py
[1, 4, 9, 16, 25, 36, 49]
l是map函数返回的一个iterator,惰性序列,保存关系x*x
,在调用list()函数的时候执行计算得到序列。
2.map()作为高阶函数,事实上抽象化了运算规则。
比如将一个list中的所有元素转化为字符形式:
l1 = map(str, [1, 2, 3, 4, 5, 6, 7])
print(l1)
print(list(l1))
<map object at 0x1013d89b0>
['1', '2', '3', '4', '5', '6', '7']
3.reduce()函数:"reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算",效果:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
比如一个求和序列:
def f1(x, y) :
return x+y
l2 = reduce(f1, [1, 2, 3, 4, 5])
print(l2)
l3 = reduce(f1, 'string')
print(list(l3))
15
['s', 't', 'r', 'i', 'n', 'g']
将数字整合起来:[1, 2, 3, 4, 5] => 12345
def f2(x, y) :
return x*10 + y
l4 = reduce(f2, [1, 2, 3, 4, 5])
print(l4)
12345
4.map(),reduce()函数相组合:
str转int(int()函数):
def func(s) :
def func1(x) :
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[x]
def func2(x, y) :
return x*10 + y
return reduce(func2, map(func1, s))
s = input()
print(func(s))
952693358
952693358
原理是先将可迭代对象str映射到由int元素组成的迭代器,即惰性序列;再将该迭代器作为参数传入reduce()函数求值。
练习:
1.利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
#!/usr/bin/env python3
def func(name) :
return name.title()
l = ['adam', 'LISA', 'barT']
itor_l = map(func, l)
print(list(itor_l))
sh-3.2# ./map2.py
['Adam', 'Lisa', 'Bart']
2.Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:
#!/usr/bin/env python3
from functools import reduce
def prod(l) :
def func(x, y) :
return x*y
return reduce(func, l)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
sh-3.2# ./map3.py
3 * 5 * 7 * 9 = 945
3.string 转 float。
#!/usr/bin/env python3
from functools import reduce
def str2float(s) :
floatlen = 0
s1 = ''
flag = True
for i in s :
if i == '.' :
flag = False
continue
else :
s1 = s1+i
if flag :
floatlen = floatlen+1
floatlen = len(s)-floatlen-1
def mapfunc(s) :
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
# return {}[]
def reductfunc(x, y) :
return x*10+y
return reduce(reductfunc, map(mapfunc, s1)) / (10 ** floatlen)
print('str2float(\'123.456\') =', str2float('123.456'))
print('str2float(\'123.978\') =', str2float('123.978'))
sh-3.2# ./map4.py
str2float('123.456') = 123.456
str2float('123.978') = 123.978
2017/2/11
Python学习札记(二十一) 函数式编程2 map/reduce的更多相关文章
- Python学习札记(二十) 函数式编程1 介绍 高阶函数介绍
参考: 函数式编程 高阶函数 Note A.函数式编程(Functional Programming)介绍 1.函数是Python内建支持的一种封装,我们通过一层一层的函数调用把复杂任务分解成简单的任 ...
- Python学习札记(二十三) 函数式编程4 sorted
参考:sorted NOTE 1.sorted,快速排序,时间复杂度O(nlogn)渐进最优. #!/usr/bin/env python3 L = [] for i in range(10): L. ...
- Python学习札记(二十七) 函数式编程8 偏函数
偏函数 NOTE 1.int()函数提供额外的base参数,默认值为10.如果传入base参数,就可以做N进制的转换: #!/usr/bin/env python3 import functools ...
- Python学习笔记二:函数式编程
1:Python中,内置函数名相当于一个变量,指向内置函数.所以可以通过函数名调用相应函数,也可以给函数名赋值,改变它的内容,如:可以把另一个函数变量赋值给它,那它就指向了所赋值的函数了. 2:高级函 ...
- Python学习札记(三十一) 面向对象编程 Object Oriented Program 2
参考:类和实例 注意理解第七点. NOTE: 1.类是抽象的模板,比如Student类,实例是根据类创建出来的一个个具体的"对象",每个对象都拥有相同的方法,但各自的数据可能不同. ...
- Python学习总结之五 -- 入门函数式编程
函数式编程 最近对Python的学习有些怠慢,最近的学习态度和学习效率确实很不好,目前这种病况正在好转. 今天,我把之前学过的Python中函数式编程简单总结一下,分享给大家,也欢迎并感谢大家提出意见 ...
- Python函数式编程,map/reduce,filter和sorted
什么是函数式编程? 与面向对象编程(Object-oriented programming)和过程式编程(Procedural programming)并列的编程范式. 最主要的特征是,函数是第一等公 ...
- 分布式基础学习【二】 —— 分布式计算系统(Map/Reduce)
二. 分布式计算(Map/Reduce) 分布式式计算,同样是一个宽泛的概念,在这里,它狭义的指代,按Google Map/Reduce框架所设计的分布式框架.在Hadoop中,分布式文件系统,很大程 ...
- Python学习札记(二十五) 函数式编程6 匿名函数
参考:匿名函数 NOTE 1.Python对匿名函数提供了有限的支持. eg. #!/usr/bin/env python3 def main(): lis = list(map(lambda x: ...
随机推荐
- phpstrom 常用默认快捷键
ctrl+j 插入活动代码提示ctrl+alt+t 当前位置插入环绕代码alt+insert 生成代码菜单ctrl+shift+n 查找文件 ctrl+q 查看代码注释ctrl+d 复制当前行ctrl ...
- 解决启动Tomcat时遇到INFO: Destroying ProtocolHandler ["ajp-apr-8009"]
问题描述: 启动Tomcat时,出现INFO: Destroying ProtocolHandler ["ajp-apr-8009"]等信息 这说明端口号被占用了... 解决方法: ...
- Python3 格式化输出 %s & %d 等
1.打印字符串 print("My name is %s" %("Alfred.Xue")) #输出效果:My name is Alfred.Xue 2.打印整 ...
- 如何制作一款HTML5 RPG游戏引擎——第二篇,烟雨+飞雪效果
今天我们来实现烟雨+飞雪效果.首先来说,一款经典的RPG游戏难免需要加入天气的变化.那么为了使我们的RPG游戏引擎更完美,我们就只好慢慢地实现它. 本文为该系列文章的第二篇,如果想了解以前的文章可以看 ...
- G729 详细使用文档
https://tools.ietf.org/html/rfc4749 git://git.linphone.org/linphone-android.git http://stackoverflow ...
- MongoDB主从复制+集群
一.读写分离的概念 读写分离,基本的原理是让主数据库处理事务性增.改.删操作(INSERT.UPDATE.DELETE),而从数据库处理SELECT查询操作.数据库复制被用来把事务性操作导致的变更同步 ...
- springBoot 整合 RabbitMQ 的坑
1.Consumer raised exception, processing can restart if the connection factory supports it. Exception ...
- openocd shell脚本
openocd.sh #! /usr/bin/expectset timeout 30spawn suexpect "密码:"send "123456\r"se ...
- hdu6215 Brute Force Sorting
地址:http://acm.split.hdu.edu.cn/showproblem.php?pid=6215 题目: Brute Force Sorting Time Limit: 1000/100 ...
- Codeforces Round #425 (Div. 2) B - Petya and Exam
地址:http://codeforces.com/contest/832/problem/B 题目: B. Petya and Exam time limit per test 2 seconds m ...