zoukankan      html  css  js  c++  java
  • day10-高阶函数

    高阶函数

    高阶函数:就是把函数当成参数传递的一种函数,例如:

    def add(x,y,f):

    return f(x)+f(y)

    print(add(-8,11,abs))

    结果:

    19

    解释:

    1. 调用add函数,分别执行abs(-8) 和abs(11),分别计算出他们的值
    2. 最后做和运算

    介绍几种常用的高阶函数

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 # @time: 2017/11/1 21:09
     4 # Author: caicai
     5 # @File: def1.py
     6 from functools import reduce
     7 ###map()函数,第一个参数为自定义函数,第二个参数为可迭代对象
     8 lt = [1,2,3,4,5]
     9 
    10 def f2(x):
    11     return x*x
    12 ml = map(f2,lt)
    13 print(type(ml))
    14 print(list(ml))
    15 print('################reduce######################',)
    16 ###reduce()函数
    17 #传入的函数必须接受两个参数,
    18 #把可迭代对象的两个参数作为函数的实参,传入到f好吃中,
    19 #把每次f运算的结果作为第一个实参,可迭代对象额下个元素作为另外一个实参,传入函数f中
    20 #以此类推,最终得到结果,
    21 def f(x,y):
    22     return x + y
    23 print(reduce(f,[1,2,3,4,5], 10 ))
    24 
    25 print('##############filter######################')
    26 #fukter函数
    27 #函数会每次把可迭代对象的元素传入进去,如果返回为true,则保留该元素,如果返回为false,则不保留该函数
    28 a = [1,2,3,4,5]
    29 def is_odd(x):
    30     return x%2 == 1
    31 print(list(filter(is_odd,a)))

    #sorted() 排序
    #对字典就行排序
    #sorted()
    mm = dict(a=2,c=1,b=3,d=4)
    print(mm)
    for i in mm:
        print(i)
    for j in mm.items():
        print(j)
    #print(mm)
    test = sorted(mm.items(),key=lambda d: d[1])
    # test = sorted(mm.items(),key =  reverse=False)
    print(test)

    输出结果

    ############sorted###########
    {'a': 2, 'c': 1, 'b': 3, 'd': 4}
    a
    c
    b
    d
    ('a', 2)
    ('c', 1)
    ('b', 3)
    ('d', 4)
    [('c', 1), ('a', 2), ('b', 3), ('d', 4)]

    匿名函数

    匿名函数:没有名字的函数
    实例
    #正常函数表示
    def sum(x,y):
        return x+y
    
    #匿名函数表示
    m = lambda x, y: x+y
    print(m(4,5))
    不要让以后的自己被嫌弃
  • 相关阅读:
    [ES6] 15. Generators -- 2
    [ES6] 14. Generator -- 1. yield & next()
    [ES6] 13. Using the ES6 spread operator ...
    [ES6] 12. Shorthand Properties in ES6
    [ES6] 11. String Templates
    计算机-DB:OLAP(联机分析处理)
    计算机-事务:OLTP(联机事务处理过程)
    软件-数据库-分布式:HBase
    架构-分布式:Hadoop
    计算机-数据仓库:DW/DWH
  • 原文地址:https://www.cnblogs.com/wxp997/p/7768803.html
Copyright © 2011-2022 走看看