Python学习基础(9):函数式编程
2016-03-03 16:18
756 查看
[0]:高阶函数,可以接受其他函数作为参数:
比如def high_func(x,f): return f(x)*f(x+1) high_func(-10,abs)
[1]map和reduce的练习,map用来将一个函数作用到一个序列的每一个element上面并且返回一个新的iterator.我们可以用list()将这个iterator变成list.reduce则可以将一个函数的结果作用到下一个元素上面,然后不停调用.
将一系列名字变成开头大写,后面小写
def normalize(L): def convert(name): return str.upper(name[0])+str.lower(name[1:]) return list(map(convert,L)) print(normalize(['alll','dFFFF']))
获得乘积
from functools import reduce def prod(L): def times(x,y): return x*y return reduce(times,L) ans = prod([1,2,3,4,5]) print(ans)
将字符串变成float版本1:
from functools import reduce def str2float(s): x,y = s.split('.') y = y[::-1] 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] def compute(x,y): return x*10+y def compute2(x,y): return x/10+y return reduce(compute,map(char2num,x))+reduce(compute2,map(char2num,y))/10 print(str2float('0.2345'))
将字符串变成float版本2,这个版本好一点,避免输入整数会出现bug.但是它用到了nonlocal变量.来确定小数点出现的位置.
from functools import reduce def str2float(s): point = 0; def char2nums(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,'.':-1}[s] def to_float(f,y): nonlocal point if(y == -1): point = 1 return f if (point == 0): return f*10+y else: point = 10*point return f+y/point nums = list(map(char2nums,s)) return reduce(to_float,nums,0.0) print(str2float('123'))
相关文章推荐
- Python 字符串、列表、字典 操作方法大全 & 正则re
- Python else与elif语句语法讲解
- 四、Opencv2.4.9和Python工具包的安装
- 深入理解Python中各种方法的运作原理(静态方法、类方法、抽象方法)
- python词云 wordcloud 入门
- 用python实现字符串的反转
- Python-----文件读写
- Python模块之pexpect
- Python-----生成器:generator
- Python中time模块详解
- python
- PEP8 Python 编码规范
- Python程序中用csv模块来操作csv文件的基本使用教程
- How to take partial screenshot with Selenium WebDriver in python
- Python:渗透测试开源项目【源码值得精读】
- python __call__ 函数
- 举例简单讲解Python中的数据存储模块shelve的用法
- Python中的数据对象持久化存储模块pickle的使用示例
- Python---__slots__
- Python练习:多人猜数字问题