zoukankan      html  css  js  c++  java
  • python之函数式编程(一)

    通常我们把可以把函数当成变量的函数,叫做高阶函数。函数式编程指的就是高阶函数编程

    例1:

    求两个数的绝对值的和。

    解析:绝对值函数abs,我们可以定义个函数,把abs当做其中一个变量

    def f(x,y,c):
        return c(x) + c(y)
    n = f (-5,6,abs)
    print n
    

    求两个数的开根后的和,也可以用同样的函数调用(求平方根使用math。sqrt函数)

    import math
    def f(x,y,c):
        return c(x) + c(y)
    n = f(9,25,math.sqrt)
    print n

    例2:

    也有python自带的高阶函数,如:map(它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。)

    求一组数的平方

    def f(x):
        return x * x
    n = map(f,[2,4,6,8])
    print n 

    将大小写混乱的英文名,输出成首字母为大写,后面为小写。首字母为大写其它小写:s[0].upper()+s[1:].lower()

    def f(s):
        return s[0].upper() + s[1:].lower()
    print map(s,['lSIa','MAck','rOsE'])

    例3:

    python自带高阶函数reduce(),reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。

    求多个数之间的想乘的结果

    def f(x,y):
        return x * y
    n = reduce(f,(2,3,4,5))
    print n

    要可以多个函数结合用,比如range函数,(求10以内的数想乘结果)

    def f(x,y):
        return x * y
    n = reduce(f,range(1,10))

    例4:

     python内置高阶函数filter的使用方法是一样的。filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

    查出1,2,3,4,5,6,7,8,9几个数中的奇数

    def f(x):
        return x % 2 == 1
    n = filter(f,range(1,10))
    print n

    同样可以用以下for循环来实现

    n = []
    for i in range(1,10):
        if i % 2 == 1:
            n.append(i)
    print n

    filter的功能是很强大的,我们再来个例子,求出1-100以内,平方根是整数的数

    import math
    def
    is_sqr(x): r = int(math.sqrt(x)) return r * r == x n = filter(is_sqr,range(1,101)) print n

    例5:

    sorted也是pyhton内置的高阶函数之一,它的作用主要在与排序。

    比如我们对下面数据进行排序

    print sorted([2,34,56,32,4])

    会得出以下结果

    [2, 4, 32, 34, 56]

    比如我们还可以用soeted对英文进行忽略大小排序

    def paixu(s1,s2):
        if s1[0].lower() < s2[0].lower():
            return -1
        if s1[0].lower() > s2[0].lower():
            return 1
        return 0
    print sorted(['bob', 'about', 'Zoo', 'Credit'],paixu)

     

  • 相关阅读:
    双 MySQL 启动、停止脚本
    Mysql 备份与恢复
    Mysql Replication 主从同步
    SYN Flood 防范
    HTTP 1.0 & 1.1
    Memcache 内存对象缓存系统
    Redis 非关系型数据库 ( Nosql )
    Keepalived 角色选举
    Keepalived 资源监控
    keepalived
  • 原文地址:https://www.cnblogs.com/haibing1230/p/9400379.html
Copyright © 2011-2022 走看看