zoukankan      html  css  js  c++  java
  • Python函数式编程(把函数作为参数传入)

    map:接受两个参数(函数,Iterable),map将传入的函数依次作用于Iterable的每个元素,并且返回新的Iterable
    def f(x):
        return x*x
    r = map(f,[1,2,3,4])    #此时的r为惰性求值——可用next()和for...in取值
    #通过list()返回全部
    print(list(r))  #[1, 4, 9, 16]
    reduce:接受两个参数(函数,序列),reduce把一个函数作用于序列上,返回的结果继续和序列的下一个元素做累积计算,其效果为:reduce(f,[x,y,z])=>f(f(x,y),z)
    from functools import reduce
    def add(x,y):
        return x+y
    reduce(add,[1,3,5,7,9]) #25
    filter:过滤序列。接受两个参数(函数,序列),filter把函数作用于序列上,根据返回值是否为True,决定是否放弃该元素
    def is_odd(x):
        return x%2==1
    list(filter(is_odd,[1,2,3,4,5,6,7,8,9]))    #filter惰性求值[1, 3, 5, 7, 9]
    sorted:排序,可排序对象包括数字list、字符串list、dict等,可接受三个参数,后两个为可选
    # sorted([],key=express,reverse=True) key:对每个元素的处理方法   reverse:是否反向排序
    sorted([0,1,-2,-1,6,3,8],key=abs,reverse=True) #[8, 6, 3, -2, 1, -1, 0]
    匿名函数 lambda:匿名函数关键字 :前的元素表示匿名函数的参数 匿名函数不用谢return表达式,返回值就是该表达式的值
    m = list(map(lambda x: x*x,[1,2,3,4]))
    print(m)    #[1, 4, 9, 16]
    装饰器:代码运行期间动态增加功能
    #在now函数运行前自动打印日志
    import functools
    def log(func):
        @functools.wraps(func)
        def wrpper(*args,**kw):
            print("call %s()" % func.__name__)
            return func(*args,**kw)
        return wrpper
    # 调用装饰器
    @log
    def now():
        print("hello")
    
    now()   #call now() hello
    偏函数:functools.partial 把函数的某些参数固定住,返回一个新的函数,使调用更简单
    import functools
    int2 = functools.partial(int,base=2)
    print(int2("1000000"))  #64
     
     
     
  • 相关阅读:
    day7
    11.3NOIP模拟赛
    codeforces 880E. Maximum Subsequence(折半搜索+双指针)
    11.2NOIP模拟赛
    bzoj1483: [HNOI2009]梦幻布丁(vector+启发式合并)
    day9
    codeforces 1006 F(折半搜索)
    codeforces 28D(dp)
    P2210 Haywire(A*)
    4800: [Ceoi2015]Ice Hockey World Championship(折半搜索)
  • 原文地址:https://www.cnblogs.com/sghy/p/8079995.html
Copyright © 2011-2022 走看看