python 学习笔记4
2017-08-05 18:01
162 查看
python learning notes 4
functional programming
1.high-order function
In python, we don’t need to worry about elemtype. In other words, if we want a pointer points to a function, it’s won’t bother us to define a complicated function pointer, just write varName=func(). Then everything is ok. Next time, you can use varName() to call this function. After this, let’s introduce high-order function. This is a function receieve a parameter that points to a function. And then you can use this parameter to call this function. This is called high-order function.Now, let’s introduce some high-order function built in python.
1. map().
map() function providea way to map a list to an map object, then use list() to transform this object to a list.
e.g.
list(map(lambda x:return x*x,range(10)))
This statement produce a list with 0,1,4,9,16,25…,100.
2. reduce().
This function receieve two parameters: one is a func name, and the other is a list. Then this function will automatically do func operation from list one by one(using the result and the next parameter in the list).Using reduce we can define a str2int function.
def mapTo(s): return {'1':1,'2':2,...'0':0}[s] def str2int(str): return reduce(lambda x,y:return 10*x+y,map(mapTo,str))
This allow us to write a transform func in just 4 lines!
One more thing to say, when we use reduce(), we need to import functools:
from functools import reduce.
3. filter().
This function is to filter element in a list. We pass it a judge function, then it judge whether to throw away this element or not depending on the return value of this judge function. Using this, we can write a piece of code to realize a programe to produce prime using steve method.#!/usr/bin/env python3 # -*- coding: utf-8 -*- def odd_num(): n=1 while True: n+=2 yield n def notDivisible(n): return lambda x:x%n>0 def prime(): yield 2 it=odd_num() while True: num=next(it) yield num it=filter(notDivisible(num),it) for i in prime(): if(i<1000): print(i) else: break
4. sorted().
sorted() is also similiar to function sort() in c++. It receieve a key function, then use it to do comparasion and sort the whole list. Key here is just map the orignal list to pointed one that allows us to do comparasion.e.g. sort the list according to the grade.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- a=[('chen',100),('bia',150),('gao',105)] a=sorted(a,key=lambda x:x[:][1]) print(a)
what’s more, we can use
reverse=Trueto sort the list in the reversal sequence.
2.Return a function.
python supports us return a function type object. And when we need call this func,just use this return value(). And inner defined function can use variables in the current function. That is to say we don’t pass parameter to it. But this raises a problem: if we write a func return multible func, and each func uses ranged variables in it, ranged variables in it are always the last one. Because return function is executed until it is called.3.Anonymous function(lambda)
There is also a lambda expression in c++ and I think they are quite similiar. The syntax is lambda x:do somthingx here is parameter, and the return value is just the value of do something. Using this we don’t have to define a small func but just to write a single line.
4.decorator.
This is also a stuff I’ve never seen in c++. To execute some statements when executing this function, but never write these statements into the function. It’s quite useful when we want to print some log of this function.#!/usr/bin/env python3 # -*- coding: utf-8 -*- import functools def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args,**kw): print('%s %s():' % (text,func.__name__)) return func(*args,**kw) return wrapper return decorator @log('execute') def now(): print('do something') @log('excute') def func2(): print('fofofo') func2() now() print(now.__name__)
When we write @log(‘execute’), that equals to write now=log(‘execute’)(now). First execute log(‘execute’) to return a decorator, then use this decorator to execute function now. But this will lead to an error: the name of now is not now, but wrapper. Because you use a decorator to execute now and assign it to now. Thus, you get a function name wrapper r
4000
ather than now. To avoid this problem, we can copy the function name to the wrapper. Again, functools provides us with this function: wraps()(using @ snytax). At last, it works as we want!
5.partial function
This tool helps us to define a new function(fix parameters in fact). We can use this tool to easily modified the function for the purpose of calling it expendiently. Before using partial function, you should import functools. Then its syntax looks like this: NewFuncName=functools.partial(funcName,*args,**kw). Take modified func int for example:import functools int2=functools.partials(int,base=2)
相关文章推荐
- Python学习笔记(4)
- python学习笔记(九)将函数存储在模块中,导入模块
- Python基础教程 第8章: 异常 学习笔记
- python学习笔记--类方法、对象方法、静态方法
- 第002讲:用Python设计第一个游戏 ---学习笔记
- Python OpenCV学习笔记之:使用MOG2视频背景消除
- VUI-百度语音之Rest接口python学习笔记0
- Python学习笔记(三):函数
- python核心编程学习笔记-2016-09-18-01-数据库编程(三)
- Python学习笔记一之列表list
- python学习笔记7(使用字符串)
- Python 学习小笔记
- Python学习笔记57(正则表达式)
- Python深入学习笔记(一)
- 第2章-1 利用Python进行数据分 学习笔记
- Python学习笔记(三)数学函数
- python学习笔记-(11)python中的文件相关
- Python学习笔记(三)
- Python3 高级功能学习笔记(面向对象和正则表达式)
- Python学习笔记(十六)----Python列表(Lists)