python 学习笔记4

来源:互联网 发布:mysql左外连接查询 编辑:程序博客网 时间:2024/05/19 04:28

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 provide
a 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 ndef notDivisible(n):    return lambda x:x%n>0def 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=True to 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 somthing
x 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 functoolsdef 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 rather 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 functoolsint2=functools.partials(int,base=2)
原创粉丝点击