Python14 higher-order functions _map, reduce

Higher-order functions

  • Higher-order functions explained:
    • Variables can point to functions
      • Example:
        # 调用abs()函数 print(abs(-10)) # abs()函数本身 print(abs) # 函数本身赋值给变量 func = abs print(func) # 调用函数 print(func(-10))
      • operation result:
        m2BSXT.png
      • The function name is variable: such as abs () function can also be seen as a variable abs
    • Higher-order function: a function can receive another function as a parameter
      • Example:
        # 高阶函数 def hfunc(x,y,function): # 参数分别是 整数,整数,函数- abs()绝对值函数 return function(x) + function(y) print(hfunc(-2,5,func)) # 输出7
  • map / reduce function
    • map () function:
      • Syntax: map(函数,Iterator), passing a function and an iterator
      • Example:
        # map()实例 def f(x): # 定义一个乘积函数 return x * x do_map= map(f,[1,2,3,4,5]) # 返回一个惰性序列 print(do_map) mlist = list(do_map) # 转换成有序的list print(mlist)
      • operation result:
        m2rCFJ.png
      • Results understood that: corresponds to the iterator is easy to see each value as the first parameter (function f) parameters within
    • reduce: reduce to a function on a sequence [x1, x2, x3, ...], the function must receive two parameters, and the reduce the result of the next element in the sequence continues to do cumulative basis, the effect is:
      # reduce 函数 def add(x,y): return x + y def fu(x,y): return x * y from functools import reduce # reduce 函数 do_reduce = reduce(fu,[1,2,3,4,5]) print(do_reduce)
    • operation result:
      m2yjyt.png
    • Appreciated: sequence corresponding to incoming x, Y (the first 1, 2) a second time as a result of the last x, sequentially as the back (y) i.e. (2,3)

Guess you like

Origin www.cnblogs.com/thloveyl/p/11409623.html