zoukankan      html  css  js  c++  java
  • python的一些高阶用法

    map的用法

    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]
    

    通过上面的运行,可以知道map就是把一个数组内所有的元素都执行map加入的方法。
    用法如下 map(方法,数组)

    reduce的用法

    先看例子

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

    通过上面的例子,直观的来看,我们可以发现reduce和map方法有一些不一样。

    1. map是python自带的函数,而reduce需要引入functools
    2. map 返回的是一个map对象,而reduce是返回的一个数字
    3. map函数需要一个参数,而reduce的参数需要两个。

    map是对一个集合中的每个元素执行指定的方法。而reduce则是依次对集合的元素调用指定的方法。先把前两个参数执行reduce以后形成的返回之作为第一个参数,再和第三个参数形成返回值,依次执行。

    filter函数

    filter则是对集合的每个元素执行一次判断,能让filter指定的函数返回真值则返回,否则则不出现在返回集合中。

    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

    顾名思义排序。用法如下

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

    返回函数(闭包)

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

    需要注意的是闭包的代码是到最后执行a(6)的时候,才调用了函数里面的执行。举个例子

    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
    

    从上面的例子中,我们如果没有理解到返回的函数是在最后加上括号的时候才调用,可能以为返回之是0,1,2,3


    但是实际上def sub()里面的内容一直都没执行,但是外面的i 一直到了3.当调用a()的时候。开始执行。所以如上面的返回结果。

    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
    

    上面的报错,需要引入关键词nonlocal 如下:

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

    匿名函数

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

    通过上面的式子我们简单可以看到lambda函数或者匿名函数的意义

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

    我们大概可以看到lambda函数的:前面相当于参数,后面的是返回数值

    装饰器

    我的理解类似java中的AOP或者.net中的面向切片编程

    '''比如调用一个方法的时候,我们期望另外一个方法也被调用。比如我们执行一个操作,期望不改变任何代码,就可以打印出来这个方法的日志'''
    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的名称发生了改变,要保持不变,需要@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'
    

    以上的内容参考学习 廖学峰的学习网站

    
    
  • 相关阅读:
    HDU 5492 Find a path
    codeforce gym 100548H The Problem to Make You Happy
    Topcoder SRM 144 Lottery
    codeforce 165E Compatible Numbers
    codeforce gym 100307H Hack Protection
    区间DP总结
    UESTC 1321 柱爷的恋爱 (区间DP)
    HDU 4283 You Are the One (区间DP)
    HDU 2476 String painter (区间DP)
    UESTC 426 Food Delivery (区间DP)
  • 原文地址:https://www.cnblogs.com/bbird/p/12150771.html
Copyright © 2011-2022 走看看