美文网首页
0_3_高阶函数、偏函数

0_3_高阶函数、偏函数

作者: li_coder | 来源:发表于2018-06-06 16:19 被阅读0次

    1. 高阶函数

    把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式

    # 加法
    def add(x, y):
        return x + y
    # 减法
    def subtract(x, y):
        return x - y
    # 两个参数,和一个接收两个参数的函数
    def and_(x, y ,func):
        return func(x, y)
    
    print(and_(1, 2, add))  # 3
    print(and_(1, 2, subtract))  # -1
    

    2. 偏函数

    将现有函数,添加默认参数,生成新的函数

    # 根据单词首字母排序,不区分大小写
    import functools
    
    word_list = ['bob', 'about', 'Zoo', 'Credit']
    my_sorted = functools.partial(sorted, key=lambda x: x[0].lower())
    sorted_list = my_sorted(word_list )
    
    

    相关文章

      网友评论

          本文标题:0_3_高阶函数、偏函数

          本文链接:https://www.haomeiwen.com/subject/qywbsftx.html