zoukankan      html  css  js  c++  java
  • python 函数式编程:高阶函数,map/reduce

    python 函数式编程:高阶函数,map/reduce

     1 #函数式编程
     2 #函数式编程一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数
     3 #(一)高阶函数
     4 
     5 f=abs
     6 f
     7 print(f(-20))
     8 #结果  20
     9 #函数可以赋值给一个变量,即:变量可以指向函数
    10 #那么函数名是什么?函数名其实就是指向函数的变量!
    11 
    12 #下面的代码,执行后,abs已经不指向求绝对值函数而是一个整数10了。
    13 #后面的abs(-10)将报错,无法执行,必须重启python才可以。
    14 #abs=10
    15 #abs(-10)
    16 
    17 #一个简单的高阶函数
    18 #所谓高阶函数,即是可以把函数作为其参数传入。
    19 def add(x,y,f):
    20     return  f(x)+f(y)
    21 
    22 print(add(-5,6,abs))
    23 
    24 #演示高阶函数map()/reduce()
    25 #map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次
    26 #作用到序列的每个元素,并把结果作为新的Iterator返回
    27 #比如我们有一个函数f(x)=x^2,要把它作用在一个list[1,2,3,4,5,6,7,8,9]上
    28 
    29 def f(x):
    30     return  x*x
    31 r=map(f,[1,2,3,4,5,6,7,8,9])
    32 #Iterator是个迭代器,即是个惰性序列,需要list()函数让它把整个序列计算出来返回一个list
    33 print(list(r))
    34 #结果 [1,4,9,16,25,36,49,64,81]
    35 
    36 #map()作为高阶函数,事实上它把运算规则抽象了。
    37 #再来一个例子,把list所有数字转为字符串
    38 print(list(map(str,[1,2,3,4,5,6,7,8])))
    39 #结果  ['1', '2', '3', '4', '5', '6', '7', '8']
    40 
    41 #reduce()函数
    42 #它的效果就是:
    43 #reduce(f,[x1,x2,x3,x4])=f(f(f(x1,x2),x3),x4)
    44 from functools import reduce
    45 def fn(x,y):
    46     return  x*10+y
    47 
    48 print(reduce(fn,[1,3,5,7,9]))
    49 #结果:13579, 即把序列转成了一个整数
    50 
    51 #另一个例子,实现int()函数的功能
    52 def str2int(s):
    53     def fn(x,y):
    54         return x*10+y
    55     def char2num(s):
    56         return {'0':0,'1':1,'2':2,'3':3,'4':4,
    57                 '5':5,'6':6,'7':7,'8':8,'9':9}[s]
    58     return reduce(fn,map(char2num,s))
    59 print(str2int('784533'))
    60 #结果  784533
    61 
    62 #还可以用lambda函数进一步简化成
    63 def char2num(s):
    64     return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
    65             '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    66 def str2int(s):
    67     return reduce(lambda x,y:x*10+y,map(char2num,s))
    68 print(str2int('743092'))
    69 #结果  743092
  • 相关阅读:
    jmeter实现文件下载
    三大主流负载均衡
    如何实现从登录接口响应数据中提取JSESSIONID
    URL构成及各个协议默认端口
    git提交代码报:fatal: Unable to create 'E:/testGit/test/.git/index.lock': File exists.
    MySql数据库慢查询
    mongdb创建自增主键(primary key)的相关讨论
    自定义延时查询控件---valen
    Systemd Unit文件中PrivateTmp字段详解-Jason.Zhi
    mysql create table
  • 原文地址:https://www.cnblogs.com/hackpig/p/8151211.html
Copyright © 2011-2022 走看看