Some higher-order usage python

map usage

def fn(x):
    return x*2
L1 = [1,2,3,4,5,6]
L2 = list(map(fn,L1))
L2
[2, 4, 6, 8, 10, 12]

Through the above operation, you can know the map is to put all the elements in an array perform the method map added.
Use the following map (process arrays)

reduce usage

Look at the example

from functools import reduce
def add(x,y):
    return x + y
L1 = [1,2,3,4,5,6]

L2 = reduce(add,L1)
L2
21

By the example above, an intuitive point of view, we can discover and map reduce some methods are not the same.

  1. python map is carrying function, and reduce the need to introduce functools
  2. map returns a map object, and reduce the number returned is a
  3. map function takes a single parameter, and reduce the need for two parameters.

A method for a map is set for each element performs specified. And that in turn reduce the specified method calls to the elements of the collection. Returns the first parameter after the formation of the first two execution reduce it as the first parameter, and then returns the value of the third parameter is formed, in sequence.

filter function

filter is performed for each element of the set is determined once, let filter specified function returns a true value is returned, otherwise not present in the returned collection.

def fn(x):
    return x%2 ==0
L1 = [1,2,3,4,5,6,7,8]
F1 = filter(fn,L1)
print(F1)
print(list(F1))
<filter object at 0x7f1d38369358>
[2, 4, 6, 8]

sorted

As the name suggests ordering. Usage is as follows

sorted(集合,key=排序的算法,reverse=True) #reverse=True如果添加反向排序

Return function (closure)

def fn(x):
    def add(y):
        return x + y
    return add
a = fn(5)
a(6)
11

Note that the code is the last closure of a (6) when it performs the function calls performed inside. for example

def fn():
    rs = []
    for i in range(4):
        def sub():
            return i
        rs.append(sub)
    return rs
a,b,c,d = fn()

print(a())
print(b())
print(c())
print(d())
3
3
3
3

From the above example, if we do not understand the function to return is when the last call before the parentheses, it is possible that return 0,1,2,3


but in fact def sub () there has been no contents execution, but i have been to outside of the time 3. when you call a () of. Begin execution. As the above result is returned.

def efn():
    i = 1
    def sub():
        i = i + 1
        return i
    return sub

t = efn()
t()
---------------------------------------------------------------------------

UnboundLocalError                         Traceback (most recent call last)

<ipython-input-15-7574f0a729df> in <module>()
      7 
      8 t = efn()
----> 9 t()


<ipython-input-15-7574f0a729df> in sub()
      2     i = 1
      3     def sub():
----> 4         i = i + 1
      5         return i
      6     return sub


UnboundLocalError: local variable 'i' referenced before assignment

Given above, the need to introduce Image nonlocal follows:

def efn():
    i = 1
    def sub():
        #关键字
        nonlocal i
        i = i + 1
        return i
    return sub

t = efn()
print(t())
print(t())
2
3

Anonymous function

list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]

We simply can see the significance of the anonymous function or lambda function by the above formula

f = lambda x,y:x + y
f(5,6)
11

We probably can see the lambda function: the equivalent of the previous parameters, return values ​​back

Decorator

My understanding-oriented programming similar slice of java or .net in AOP

'''比如调用一个方法的时候,我们期望另外一个方法也被调用。比如我们执行一个操作,期望不改变任何代码,就可以打印出来这个方法的日志'''
def log(func):
    def wraper(*args,**kw):
        print(func.__name__+' is call to log')
        return func(*args,**kw)
    return wraper

@log
def fn():
    print('this is fn')
    
fn()
fn is call to log
this is fn
''' 如果我们希望往log里面传递参数'''
def log(text):
    def decorator(func):
        def wraper(*args,**kw):
            print(func.__name__+' is call to log ' + text)
            return func(*args,**kw)
        return wraper
    return decorator
@log('hello')
def fn():
    print('fn')
fn()
fn.__name__
fn is call to log hello
fn





'wraper'

fn name changed to remain the same, you need @ functools.wraps (func)

''' 如果我们希望往log里面传递参数'''
import functools
def log(text):
    def decorator(func):
        @functools.wraps(func)
        def wraper(*args,**kw):
            print(func.__name__+' is call to log ' + text)
            return func(*args,**kw)
        return wraper
    return decorator
@log('hello')
def fn():
    print('fn')
fn()
fn.__name__
fn is call to log hello
fn





'fn'

The contents of the above reference learning Liao Xuefeng learning website

Guess you like

Origin www.cnblogs.com/bbird/p/12150771.html